blob: 49593fa9df86e82b40fa24d4cd1c88709fa52c48 [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 maka_agent_facts::{
artifact::ArtifactSource,
attachment::{
MAX_INLINE_EXTERNAL_TEXT_BYTES, StorageRef, native_image_extension,
sanitize_attachment_filename,
},
};
use maka_agent_state::artifacts::{ArtifactStore, SessionScope};
use std::{collections::BTreeSet, io::Write};
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Image {
path: String,
media_type: String,
}
struct MaterializedFile {
name: String,
mime_type: String,
bytes: u64,
path: String,
}
pub(super) struct Materials {
pub message: String,
pub images: Vec<Image>,
directory: Option<PathBuf>,
}
impl Materials {
pub fn handoff(&mut self) -> Option<PathBuf> {
self.directory.take()
}
}
impl Drop for Materials {
fn drop(&mut self) {
if let Some(dir) = self.directory.take()
&& let Err(error) = remove_materialized_dir(&dir)
{
tracing::warn!(
path = %dir.display(),
%error,
"Failed to remove unhanded external attachment directory"
);
}
}
}
enum Media {
Image(&'static str),
InlineText,
LocalFile,
}
impl Media {
fn classify(mime: &str, bytes: u64) -> Self {
if let Some(extension) = native_image_extension(mime) {
return Self::Image(extension);
}
if (mime == "application/json" || mime.starts_with("text/"))
&& bytes <= MAX_INLINE_EXTERNAL_TEXT_BYTES as u64
{
return Self::InlineText;
}
Self::LocalFile
}
}
pub(super) fn render_message_text(
content: &maka_agent_facts::input::MessageInput,
language: maka_agent_facts::language::Language,
) -> Result<String, Error> {
let mut sections = Vec::new();
if !content.text.is_empty() {
sections.push(content.text.clone());
}
if let Some(quotes) = content.quotes.as_deref().filter(|q| !q.is_empty()) {
sections.push(
maka_agent_facts::input::render_quotes(quotes, language).map_err(Error::Invalid)?,
);
}
if let Some(dirs) = content
.directory_references
.as_deref()
.filter(|d| !d.is_empty())
{
sections.push(
maka_agent_facts::input::render_directory_references(dirs, language)
.map_err(Error::Invalid)?,
);
}
if let Some(rendered) =
maka_agent_facts::input::render_session_references(&content.text, language)
{
sections.push(rendered);
}
Ok(sections.join("\n\n"))
}
pub(super) async fn prepare(
store: &ArtifactStore,
scope: &SessionScope,
content: &maka_agent_facts::input::MessageInput,
language: maka_agent_facts::language::Language,
cancellation: &CancellationToken,
material_root: &std::path::Path,
) -> Result<Materials, Error> {
let mut materials = Materials {
message: render_message_text(content, language)?,
images: Vec::new(),
directory: None,
};
let mut materialized_files = Vec::new();
let mut seen = BTreeSet::new();
for (index, attachment) in content.attachments.iter().flatten().enumerate() {
let StorageRef::SessionFile {
session_id,
relative_path,
} = &attachment.storage_ref
else {
return Err(Error::Invalid(
"External agent attachment must be a session user upload".into(),
));
};
if session_id != &scope.session || !seen.insert(relative_path) {
return Err(Error::Invalid(
"External agent attachment must be a distinct upload owned by this session".into(),
));
}
let attachment = attachment.clone();
let material_root = material_root.to_owned();
let cancellation = cancellation.clone();
// The artifact reader owns the blocking snapshot and all payload I/O;
// metadata, source and digest are checked together, not in a second lookup.
let (updated, local_file) = store
.with_content(
scope.clone(),
relative_path.clone(),
move |record, reader| -> Result<(Materials, Option<MaterializedFile>), Error> {
record
.validate_attachment(&attachment)
.map_err(|e| Error::Invalid(e.to_string()))?;
if record.source != ArtifactSource::UserUpload {
return Err(Error::Invalid(
"External agent attachment is not an immutable user upload".into(),
));
}
let digest = record.summary.as_deref().ok_or_else(|| {
Error::Invalid("External agent upload digest missing".into())
})?;
let media = Media::classify(&attachment.mime_type, attachment.bytes);
let mut text = Vec::new();
let mut output = match media {
Media::InlineText => None,
Media::Image(extension) => {
let root = ensure_directory(&mut materials.directory, &material_root)?
.canonicalize()
.map_err(io_error)?;
let path =
root.join(format!("{}.{}", materials.images.len(), extension));
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("External agent image path is not UTF-8".into())
})?;
materials.images.push(Image {
path: utf8,
media_type: attachment.mime_type.clone(),
});
Some((file, path, None))
}
Media::LocalFile => {
let (file, path, utf8) = create_local_file(
&mut materials.directory,
&material_root,
index,
&attachment.name,
)?;
Some((file, path, Some(utf8)))
}
};
let mut hash = Sha256::new();
let mut remaining = attachment.bytes;
let mut buffer = [0u8; 64 * 1024];
while remaining > 0 {
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
let length = remaining.min(buffer.len() as u64) as usize;
let chunk = &mut buffer[..length];
reader.read_exact(chunk).map_err(io_error)?;
hash.update(&*chunk);
match &mut output {
Some((file, _, _)) => file.write_all(chunk).map_err(io_error)?,
None => text.extend_from_slice(chunk),
}
remaining -= length as u64;
}
if format!("sha256:{}", hex::encode(hash.finalize())) != digest {
return Err(Error::Invalid(
"External agent upload digest mismatch".into(),
));
}
let local_file = match output {
Some((mut file, path, Some(utf8))) => {
file.flush().map_err(io_error)?;
drop(file);
mark_read_only(&path)?;
Some(MaterializedFile {
name: attachment.name.clone(),
mime_type: attachment.mime_type.clone(),
bytes: attachment.bytes,
path: utf8,
})
}
Some((mut file, _, None)) => {
file.flush().map_err(io_error)?;
None
}
None => match String::from_utf8(text) {
Ok(text) if !text.contains('\0') => {
materials.message.push_str(&format!(
"\n\n--- Attachment {} ({}) ---\n{}\n--- End attachment ---",
serde_json::to_string(&attachment.name)
.expect("attachment name"),
attachment.mime_type,
text,
));
None
}
Ok(text) => Some(write_local_bytes(
&mut materials.directory,
&material_root,
index,
&attachment,
text.as_bytes(),
)?),
Err(error) => Some(write_local_bytes(
&mut materials.directory,
&material_root,
index,
&attachment,
error.as_bytes(),
)?),
},
};
Ok((materials, local_file))
},
)
.await
.map_err(|e| Error::Persistence(e.to_string()))?
.ok_or_else(|| Error::Invalid("External agent user upload unavailable".into()))??;
materials = updated;
if let Some(local_file) = local_file {
materialized_files.push(local_file);
}
}
if !materialized_files.is_empty() {
if !materials.message.is_empty() {
materials.message.push_str("\n\n");
}
materials
.message
.push_str("--- Attached files (read-only local copies for this turn) ---");
for file in materialized_files {
materials.message.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"),
));
}
materials.message.push_str("\n--- End attached files ---");
}
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
Ok(materials)
}
fn ensure_directory<'a>(
directory: &'a mut Option<PathBuf>,
material_root: &std::path::Path,
) -> Result<&'a std::path::Path, Error> {
if directory.is_none() {
*directory = Some(
tempfile::Builder::new()
.prefix("maka-native-")
.tempdir_in(material_root)
.map_err(io_error)?
.keep(),
);
}
Ok(directory.as_deref().expect("material directory"))
}
fn create_local_file(
directory: &mut Option<PathBuf>,
material_root: &std::path::Path,
index: usize,
original_name: &str,
) -> Result<(std::fs::File, PathBuf, String), Error> {
let root = ensure_directory(directory, material_root)?
.canonicalize()
.map_err(io_error)?;
let files_dir = root.join("files");
match std::fs::create_dir(&files_dir) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(io_error(error)),
}
let slot_dir = files_dir.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("External agent attachment path is not UTF-8".into()))?;
Ok((file, path, utf8))
}
fn write_local_bytes(
directory: &mut Option<PathBuf>,
material_root: &std::path::Path,
index: usize,
attachment: &maka_agent_facts::attachment::AttachmentRef,
bytes: &[u8],
) -> Result<MaterializedFile, Error> {
let (mut file, path, utf8) =
create_local_file(directory, material_root, index, &attachment.name)?;
file.write_all(bytes).map_err(io_error)?;
file.flush().map_err(io_error)?;
drop(file);
mark_read_only(&path)?;
Ok(MaterializedFile {
name: attachment.name.clone(),
mime_type: attachment.mime_type.clone(),
bytes: attachment.bytes,
path: utf8,
})
}
fn mark_read_only(path: &std::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(super) fn remove_materialized_dir(dir: &std::path::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: &std::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::Provider(format!("External agent attachment I/O failed: {error}"))
}
#[cfg(test)]
mod tests {
use super::*;
use maka_agent_facts::{
artifact::{Artifact, ArtifactKind, content_digest},
attachment::{AttachmentKind, AttachmentRef},
input::MessageInput,
language::Language,
};
use maka_agent_state::artifacts::Upload;
use serde_json::json;
#[test]
fn render_message_text_preserves_quotes_directories_and_session_references() {
let room_id = "ma_8b708bb06d73d5d83a9265c0464928803a7478a2a9083b6c3647cfc8c7c0f102_f2534dfc81315ef2b71faf2ad291705f";
let input: MessageInput = serde_json::from_value(json!({
"text": format!("请参考 [#Reviewers需要关注的事项](maka://session/{room_id}) 做一下审查"),
"quotes": [{
"text": "边界条件必须由类型约束保证。",
"label": "AGENTS.md"
}],
"directory_references": [{
"hostId": "local",
"path": "/tmp/example-dir"
}]
}))
.unwrap();
let rendered = render_message_text(&input, Language::ZH_CN).unwrap();
assert!(
rendered.contains(r#"<quoted_excerpt label="AGENTS.md">"#),
"{rendered}"
);
assert!(
rendered.contains("边界条件必须由类型约束保证。"),
"{rendered}"
);
assert!(rendered.contains("<directory_references>"), "{rendered}");
assert!(rendered.contains("/tmp/example-dir"), "{rendered}");
assert!(rendered.contains("<session_references>"), "{rendered}");
assert!(
rendered.contains(&format!(r#"{{"path":"maka://session/{room_id}"}}"#)),
"{rendered}"
);
}
async fn upload_fixture(
store: &ArtifactStore,
scope: &SessionScope,
id: &str,
name: &str,
mime_type: &str,
bytes: Vec<u8>,
) -> AttachmentRef {
let size = bytes.len() as u64;
let artifact_id = maka_agent_facts::artifact::upload_artifact_id(&scope.session, id);
let record = Artifact {
id: artifact_id.clone(),
session_id: scope.session.clone(),
turn_id: format!("upload_{id}"),
created_at: 1,
name: name.into(),
kind: if mime_type.starts_with("image/") {
ArtifactKind::Image
} else if mime_type == "application/pdf" {
ArtifactKind::Pdf
} else {
ArtifactKind::File
},
size_bytes: size,
mime_type: Some(mime_type.into()),
source: ArtifactSource::UserUpload,
summary: Some(content_digest(&bytes)),
};
store
.upload(Upload::new(
scope.clone(),
format!("op-{id}"),
id.into(),
record,
bytes,
))
.await
.unwrap();
AttachmentRef {
kind: AttachmentKind::from_metadata(mime_type, name),
name: name.into(),
mime_type: mime_type.into(),
bytes: size,
storage_ref: StorageRef::SessionFile {
session_id: scope.session.clone(),
relative_path: artifact_id,
},
}
}
#[tokio::test]
async fn prepare_materializes_media_large_text_and_duplicate_names_as_read_only_files() {
let dir = tempfile::tempdir().unwrap();
let root_owner = maka_event_log::root::RootOwner::create(
&dir.path().join("root"),
&maka_event_log::root::RootNamespaces {
ownership: dir.path().join("owners"),
control: dir.path().join("control"),
},
)
.unwrap();
let mut migrations = maka_event_log::ROOT_MIGRATIONS.to_vec();
migrations.extend_from_slice(maka_agent_state::MIGRATIONS);
migrations.sort_by_key(|migration| migration.version);
let root = maka_event_log::RootStore::open(Arc::new(root_owner), &migrations)
.await
.unwrap();
let data = root.data_writer().unwrap();
let store = ArtifactStore::new(data);
let scope = SessionScope {
owner: serde_json::from_value(json!({
"deployment": uuid::Uuid::new_v4(),
"namespace": [uuid::Uuid::new_v4()]
}))
.unwrap(),
session: "session-1".into(),
};
let material_root = dir.path().join("inputs");
std::fs::create_dir(&material_root).unwrap();
let png = b"\x89PNG\r\n\x1a\nfake-png".to_vec();
let mp4 = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom".to_vec();
let small_txt = b"hello small text".to_vec();
let large_txt = vec![b'a'; MAX_INLINE_EXTERNAL_TEXT_BYTES + 16];
let invalid_utf8_txt = vec![0xff, 0xfe, 0xfd];
let attachments = vec![
upload_fixture(
&store,
&scope,
"att-png",
"shot.png",
"image/png",
png.clone(),
)
.await,
upload_fixture(
&store,
&scope,
"att-mp4-1",
"workgroup-weird.mp4",
"application/octet-stream",
mp4.clone(),
)
.await,
upload_fixture(
&store,
&scope,
"att-mp4-2",
"workgroup-weird.mp4",
"video/mp4",
b"second-video".to_vec(),
)
.await,
upload_fixture(
&store,
&scope,
"att-small",
"notes.txt",
"text/plain",
small_txt.clone(),
)
.await,
upload_fixture(
&store,
&scope,
"att-large",
"huge.log",
"text/plain",
large_txt.clone(),
)
.await,
upload_fixture(
&store,
&scope,
"att-bad-utf8",
"../evil/bad.txt",
"text/plain",
invalid_utf8_txt.clone(),
)
.await,
];
let mut input = MessageInput::from("look at these");
input.attachments = Some(attachments);
let materials = prepare(
&store,
&scope,
&input,
Language::EN,
&CancellationToken::new(),
&material_root,
)
.await
.unwrap();
assert_eq!(materials.images.len(), 1);
assert_eq!(std::fs::read(&materials.images[0].path).unwrap(), png);
assert!(materials.message.contains("hello small text"));
assert!(!materials.message.contains(&"a".repeat(256)));
assert!(
materials
.message
.contains("--- Attached files (read-only local copies for this turn) ---")
);
let paths: Vec<PathBuf> = materials
.message
.lines()
.filter_map(|line| {
let (_, raw) = line.split_once(", path: ")?;
let path: String = serde_json::from_str(raw).ok()?;
Some(PathBuf::from(path))
})
.collect();
assert_eq!(paths.len(), 4, "prompt: {}", materials.message);
assert_ne!(paths[0], paths[1], "duplicate filenames must not collide");
assert_eq!(
paths[0].file_name().and_then(|n| n.to_str()),
Some("workgroup-weird.mp4")
);
assert_eq!(
paths[1].file_name().and_then(|n| n.to_str()),
Some("workgroup-weird.mp4")
);
assert_eq!(
paths[2].file_name().and_then(|n| n.to_str()),
Some("huge.log")
);
assert_eq!(
paths[3].file_name().and_then(|n| n.to_str()),
Some("bad.txt")
);
assert_eq!(std::fs::read(&paths[0]).unwrap(), mp4);
assert_eq!(std::fs::read(&paths[1]).unwrap(), b"second-video");
assert_eq!(std::fs::read(&paths[2]).unwrap(), large_txt);
assert_eq!(std::fs::read(&paths[3]).unwrap(), invalid_utf8_txt);
for path in &paths {
assert!(path.starts_with(material_root.canonicalize().unwrap()));
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 mut materials = materials;
let handed_off = materials.handoff().unwrap();
assert!(handed_off.exists());
remove_materialized_dir(&handed_off).unwrap();
assert!(!handed_off.exists());
}
}