Skip to content
Open
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
629 changes: 614 additions & 15 deletions plugins/agent/engine/src/history/canonical_prompt.rs

Large diffs are not rendered by default.

75 changes: 70 additions & 5 deletions plugins/agent/engine/src/history/canonical_prompt/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,28 @@ async fn index_content(
r[1] = store.text_node(f.text(1)?).await?;
r[2] = store.json_node(f.json(4)).await?;
} else {
r[0] = 2;
let data = Fields::open(&f.value(2)?.source, &["data"], budget).await?;
let range = decode_media(store, data.text(0)?, budget, cancel).await?;
r[1] = range.start;
r[2] = range.end;
let data = Fields::open(
&f.value(2)?.source,
&["type", "data", "digest", "bytes"],
budget,
)
.await?;
if data.is(0, "ref", budget).await? {
let digest_text = read_bounded_text(data.text(2)?, 128, budget, cancel).await?;
let expected_bytes = json::u64_value(&data.value(3)?.source, budget.clone()).await?;
let (slot, digest_bytes) = store.lookup_external_media(&digest_text, expected_bytes)?;
r[0] = 3;
r[1] = slot as u64;
r[2] = expected_bytes;
put_digest(&mut r[6..10], digest_bytes);
} else if data.is(0, "data", budget).await? {
r[0] = 2;
let range = decode_media(store, data.text(1)?, budget, cancel).await?;
r[1] = range.start;
r[2] = range.end;
} else {
return Err(invalid());
}
r[3] = store.text_node(f.text(3)?).await?;
if let Some(options) = f.json(4)
&& let Some(detail) =
Expand Down Expand Up @@ -374,6 +391,37 @@ fn index_result<'a>(
Ok(r)
})
}
async fn read_bounded_text(
source: TextSource,
max_bytes: usize,
budget: &Arc<dyn SourceBudget>,
cancel: &CancellationToken,
) -> io::Result<String> {
let mut cursor = text::cursor(source, budget.clone());
let mut buffer = budget.allocate(max_bytes.clamp(64, 4096)).await?;
let mut out = Vec::new();
loop {
if cancel.is_cancelled() {
return Err(crate::preparation_cancelled(
"canonical media capture cancelled",
));
}
let read = cursor.read_chunk(buffer).await?;
buffer = read.buffer;
if out.len().saturating_add(read.bytes_read) > max_bytes {
return Err(invalid());
}
out.extend_from_slice(&buffer.as_ref()[..read.bytes_read]);
if read.eof {
break;
}
if read.bytes_read == 0 {
return Err(invalid());
}
}
String::from_utf8(out).map_err(|_| invalid())
}

async fn decode_media(
store: &Store,
data: TextSource,
Expand Down Expand Up @@ -560,6 +608,23 @@ impl Decode for ContentRecipe {
},
provider_options: store.read_json(r[5]).await?,
}),
3 => {
let slot = usize::try_from(r[1]).map_err(|_| invalid())?;
let expected_digest = digest(&r[6..10]);
let bytes = store.external_media_bytes(slot, r[2], expected_digest)?;
Ok(Self::Media {
media: MediaSource {
bytes,
media_type: store.read_text(r[3]).await?,
detail: if r[4] == 0 {
None
} else {
Some(store.read_text(r[4]).await?)
},
},
provider_options: store.read_json(r[5]).await?,
})
}
_ => Err(invalid()),
}
})
Expand Down
22 changes: 22 additions & 0 deletions plugins/agent/engine/src/history/request_backing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,28 @@ impl RequestBackingBuilder {
Ok(start..self.length)
}

/// Rewind unsealed trailing bytes appended since `position` (e.g. a deduplicated media write).
pub(crate) fn truncate_unsealed(&mut self, position: u64) -> io::Result<()> {
if position < self.sealed || position > self.length {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"cannot truncate past sealed prefix or length",
));
}
match self.storage.as_mut().expect("unfinished backing") {
Building::Resident { bytes, .. } => {
bytes
.truncate(usize::try_from(position).map_err(|_| io::Error::other("overflow"))?);
}
Building::File { file, .. } => {
file.set_len(position)?;
file.seek(SeekFrom::Start(position))?;
}
}
self.length = position;
Ok(())
}

/// Reserve a new zero-filled table in this backing; file regions stay sparse.
pub(crate) fn reserve_zeroed(&mut self, bytes: u64) -> io::Result<Range<u64>> {
let start = self.length;
Expand Down
60 changes: 48 additions & 12 deletions plugins/agent/engine/src/history/serialize_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

//! Logical message JSON emitted directly from immutable typed recipes.
use maka_agent_facts::model::prompt_source::source::*;
use maka_agent_facts::{durable::ContentRef, model::prompt_source::source::*};
use maka_provider_protocol::json_stream::pull::{JsonEscape, Transform};
use std::{future::Future, io, pin::Pin, sync::Arc};
use tokio_util::sync::CancellationToken;
Expand All @@ -32,6 +32,15 @@ pub(crate) trait AsyncEmit: Send {
bytes: &'a [u8],
) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>;
}

pub(crate) trait MediaExternalizer: Send {
fn capture<'a>(
&'a mut self,
bytes: SourceBytes,
budget: &'a Arc<dyn SourceBudget>,
cancellation: &'a CancellationToken,
) -> Pin<Box<dyn Future<Output = io::Result<ContentRef>> + Send + 'a>>;
}
type MediaLabel<'a> = dyn FnMut(usize, &ContentRecipe) -> io::Result<TextSource> + Send + 'a;
struct SyncEmit<'a, F>(&'a mut F);
impl<F: FnMut(&[u8]) -> io::Result<()> + Send> AsyncEmit for SyncEmit<'_, F> {
Expand Down Expand Up @@ -63,6 +72,7 @@ pub(crate) async fn message_async<'a>(
cancellation,
emit,
media,
externalizer: None,
preserve_media: false,
}
.message(message)
Expand All @@ -75,25 +85,40 @@ pub(crate) async fn exact_message_async(
cancellation: &CancellationToken,
emit: &mut dyn AsyncEmit,
) -> io::Result<()> {
exact_message_async_with_media(message, budget, cancellation, emit, None).await
}

pub(crate) async fn exact_message_async_with_media(
message: &MessageRecipe,
budget: &Arc<dyn SourceBudget>,
cancellation: &CancellationToken,
emit: &mut dyn AsyncEmit,
externalizer: Option<&mut dyn MediaExternalizer>,
) -> io::Result<()> {
let mut no_label = |_: usize, _: &ContentRecipe| {
Err(io::Error::other("exact serialization never labels media"))
};
Encoder {
budget,
cancellation,
emit,
media: &mut |_, _| Err(io::Error::other("exact serialization never labels media")),
media: &mut no_label,
externalizer,
preserve_media: true,
}
.message(message)
.await
}

struct Encoder<'a> {
struct Encoder<'a, 'b> {
budget: &'a Arc<dyn SourceBudget>,
cancellation: &'a CancellationToken,
emit: &'a mut dyn AsyncEmit,
media: &'a mut MediaLabel<'a>,
externalizer: Option<&'b mut dyn MediaExternalizer>,
preserve_media: bool,
}
impl Encoder<'_> {
impl Encoder<'_, '_> {
async fn literal(&mut self, bytes: &[u8]) -> io::Result<()> {
if self.cancellation.is_cancelled() {
return Err(crate::preparation_cancelled(
Expand Down Expand Up @@ -272,16 +297,27 @@ impl Encoder<'_> {
} = &part
&& self.preserve_media
{
self.literal(b"{\"type\":\"file\",\"mediaType\":").await?;
self.literal(br#"{"type":"file","mediaType":"#).await?;
self.text(&media.media_type).await?;
self.literal(b",\"data\":{\"type\":\"data\",\"data\":\"")
if let Some(externalizer) = self.externalizer.as_mut() {
let reference = externalizer
.capture(media.bytes.clone(), self.budget, self.cancellation)
.await?;
self.literal(br#","data":{"type":"ref","digest":""#).await?;
self.literal(reference.digest.as_bytes()).await?;
self.literal(br#"","bytes":"#).await?;
let bytes_text = reference.bytes.to_string();
self.literal(bytes_text.as_bytes()).await?;
self.literal(b"}").await?;
} else {
self.literal(br#","data":{"type":"data","data":""#).await?;
self.transformed(
media.bytes.clone(),
maka_provider_protocol::json_stream::pull::Base64Encoder::new(),
)
.await?;
self.transformed(
media.bytes.clone(),
maka_provider_protocol::json_stream::pull::Base64Encoder::new(),
)
.await?;
self.literal(b"\"}").await?;
self.literal(br#""}"#).await?;
}
self.exact_media_options(media, provider_options).await?;
self.literal(b"}").await?;
index += 1;
Expand Down
Loading
Loading