Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1658
akode-rs/core/src/context_manager/history.rs
Normal file
1658
akode-rs/core/src/context_manager/history.rs
Normal file
File diff suppressed because it is too large
Load Diff
360
akode-rs/core/src/context_manager/history_rejected_audio.rs
Normal file
360
akode-rs/core/src/context_manager/history_rejected_audio.rs
Normal file
@@ -0,0 +1,360 @@
|
||||
//! Non-mutating request projection for uploaded audio rejected by Responses.
|
||||
//! Provider errors are attributed only against the immutable submitted request.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_attachment_store::AttachmentStore;
|
||||
use akode_history::AcceptedFileAudio;
|
||||
use akode_history::CodexHarnessMetadata;
|
||||
use akode_history::ResponseItemEnvelope;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
use akode_protocol::models::AudioReference;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::ImageReference;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use futures::StreamExt;
|
||||
use futures::stream;
|
||||
|
||||
/// Exact file identity proven by a terminal provider error and its submitted request.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RejectedAudioFileIds(pub(crate) Vec<String>);
|
||||
|
||||
pub(crate) fn pending_audio_confirmation(
|
||||
previous: Option<&AcceptedFileAudio>,
|
||||
turn_id: &str,
|
||||
model: &str,
|
||||
provider: &str,
|
||||
items: &[ResponseItem],
|
||||
) -> Option<AcceptedFileAudio> {
|
||||
let ids = items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
ResponseItem::Message { content, .. } => Some(content.iter()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.filter_map(|part| match part {
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::File { file_id },
|
||||
} => Some(file_id),
|
||||
_ => None,
|
||||
});
|
||||
if ids
|
||||
.clone()
|
||||
.all(|id| previous.is_some_and(|known| known.file_ids.contains(id)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(AcceptedFileAudio {
|
||||
turn_id: turn_id.to_owned(),
|
||||
model: model.to_owned(),
|
||||
provider: provider.to_owned(),
|
||||
file_ids: ids.cloned().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
enum FileErrorSource<'a> {
|
||||
Audio(&'a str),
|
||||
InlineAudio,
|
||||
FileImage,
|
||||
Opaque,
|
||||
}
|
||||
|
||||
fn visit_sources<'a>(item: &'a ResponseItem, mut visit: impl FnMut(FileErrorSource<'a>)) {
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
for part in content {
|
||||
match part {
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::File { file_id },
|
||||
} => visit(FileErrorSource::Audio(file_id)),
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline { .. },
|
||||
} => visit(FileErrorSource::InlineAudio),
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File { .. },
|
||||
..
|
||||
} => visit(FileErrorSource::FileImage),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
for part in output.content_items().unwrap_or_default() {
|
||||
match part {
|
||||
FunctionCallOutputContentItem::InputAudio { .. } => {
|
||||
visit(FileErrorSource::InlineAudio)
|
||||
}
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File { .. },
|
||||
..
|
||||
} => visit(FileErrorSource::FileImage),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. } => {
|
||||
visit(FileErrorSource::Opaque)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Older opaque checkpoints carry no provenance and continue to compete for attribution.
|
||||
pub(crate) fn checkpoint_input_has_no_file_error_sources(items: &[ResponseItemEnvelope]) -> bool {
|
||||
items.iter().all(|envelope| {
|
||||
let mut clear = true;
|
||||
visit_sources(&envelope.item, |source| {
|
||||
clear &= matches!(source, FileErrorSource::Opaque)
|
||||
&& clear_checkpoint(&envelope.item, envelope.metadata.as_ref()).is_some();
|
||||
});
|
||||
clear
|
||||
})
|
||||
}
|
||||
|
||||
/// Only the host marker on this ciphertext proves that the checkpoint had no competing files.
|
||||
pub(crate) fn clear_checkpoint<'a>(
|
||||
item: &'a ResponseItem,
|
||||
metadata: Option<&CodexHarnessMetadata>,
|
||||
) -> Option<&'a str> {
|
||||
metadata.filter(|metadata| metadata.compaction_without_file_error_sources)?;
|
||||
opaque_content(item)
|
||||
}
|
||||
|
||||
fn opaque_content(item: &ResponseItem) -> Option<&str> {
|
||||
match item {
|
||||
ResponseItem::Compaction {
|
||||
encrypted_content, ..
|
||||
} => Some(encrypted_content),
|
||||
ResponseItem::ContextCompaction {
|
||||
encrypted_content, ..
|
||||
} => encrypted_content.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio IDs and competing sources in the immutable submitted request. The prompt itself
|
||||
/// can be released while the provider streams.
|
||||
pub(crate) struct SubmittedFileAudio {
|
||||
file_ids: Vec<String>,
|
||||
candidate: Option<usize>,
|
||||
has_inline_audio: bool,
|
||||
has_file_image: bool,
|
||||
}
|
||||
|
||||
impl SubmittedFileAudio {
|
||||
pub(crate) fn from_request<'a>(
|
||||
items: &[ResponseItem],
|
||||
accepted: Option<&AcceptedFileAudio>,
|
||||
clear_checkpoints: impl Iterator<Item = &'a str> + Clone,
|
||||
) -> Option<Self> {
|
||||
let mut file_ids = Vec::new();
|
||||
let mut has_inline_audio = false;
|
||||
let mut has_file_image = false;
|
||||
let mut unknown_checkpoint = false;
|
||||
for item in items {
|
||||
visit_sources(item, |source| match source {
|
||||
FileErrorSource::Audio(id) => file_ids.push(id),
|
||||
FileErrorSource::InlineAudio => has_inline_audio = true,
|
||||
FileErrorSource::FileImage => has_file_image = true,
|
||||
FileErrorSource::Opaque => {
|
||||
unknown_checkpoint |= !opaque_content(item).is_some_and(|ciphertext| {
|
||||
clear_checkpoints.clone().any(|known| known == ciphertext)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if file_ids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let candidate = if unknown_checkpoint {
|
||||
None
|
||||
} else if file_ids.len() == 1 {
|
||||
Some(0)
|
||||
} else {
|
||||
let mut unseen = file_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, id)| !accepted.is_some_and(|known| known.file_ids.contains(**id)));
|
||||
let first = unseen.next().map(|(index, _)| index);
|
||||
first.filter(|_| unseen.next().is_none())
|
||||
};
|
||||
Some(Self {
|
||||
file_ids: file_ids.into_iter().map(str::to_owned).collect(),
|
||||
candidate,
|
||||
has_inline_audio,
|
||||
has_file_image,
|
||||
})
|
||||
}
|
||||
|
||||
fn rejected_index(&self, error: &CodexErrorDetails) -> Option<usize> {
|
||||
let index = self.candidate?;
|
||||
let unique_file = self.file_ids.len() == 1;
|
||||
let attributable = match error {
|
||||
CodexErrorDetails::InvalidAudioInput { per_recording, .. } => {
|
||||
!self.has_inline_audio && (unique_file || *per_recording)
|
||||
}
|
||||
_ => unique_file && !self.has_file_image && is_unknown_file_error(error),
|
||||
};
|
||||
attributable.then_some(index)
|
||||
}
|
||||
|
||||
pub(crate) fn matches_rejection(&self, error: &CodexErrorDetails) -> bool {
|
||||
self.rejected_index(error).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn rejected_file_id(mut self, error: &CodexErrorDetails) -> Option<String> {
|
||||
let index = self.rejected_index(error)?;
|
||||
Some(self.file_ids.swap_remove(index))
|
||||
}
|
||||
|
||||
pub(crate) async fn rejected_file_ids(
|
||||
mut self,
|
||||
error: &CodexErrorDetails,
|
||||
store: &dyn AttachmentStore,
|
||||
) -> Vec<String> {
|
||||
if let Some(index) = self.rejected_index(error) {
|
||||
return vec![self.file_ids.swap_remove(index)];
|
||||
}
|
||||
if is_unknown_file_error(error) {
|
||||
// A file that decoded successfully may since have expired. Probe only IDs from
|
||||
// this submission; later queued input cannot be blamed for the provider's 404.
|
||||
self.file_ids.sort_unstable();
|
||||
self.file_ids.dedup();
|
||||
return unavailable_file_audio_ids(self.file_ids, store)
|
||||
.await
|
||||
.into_iter()
|
||||
.collect();
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn is_unknown_file_error(error: &CodexErrorDetails) -> bool {
|
||||
const UNKNOWN_FILE: &str = "Invalid input: Unknown `file_id` in input content.";
|
||||
matches!(error, CodexErrorDetails::UnexpectedStatus(response)
|
||||
if response.status == http::StatusCode::NOT_FOUND
|
||||
&& (response.body.trim() == UNKNOWN_FILE
|
||||
|| response.extract_error_message().as_deref() == Some(UNKNOWN_FILE)))
|
||||
}
|
||||
|
||||
/// A long-lived thread can reach compaction after an earlier upload has expired.
|
||||
/// Only an authoritative negative availability check permits omitting the file.
|
||||
pub(crate) async fn unavailable_file_audio(
|
||||
items: &[ResponseItem],
|
||||
store: &dyn AttachmentStore,
|
||||
) -> BTreeSet<String> {
|
||||
let mut ids = BTreeSet::new();
|
||||
for item in items {
|
||||
if let ResponseItem::Message { content, .. } = item {
|
||||
for part in content {
|
||||
if let ContentItem::InputAudio {
|
||||
audio: AudioReference::File { file_id },
|
||||
} = part
|
||||
{
|
||||
ids.insert(file_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
unavailable_file_audio_ids(ids, store).await
|
||||
}
|
||||
|
||||
async fn unavailable_file_audio_ids(
|
||||
ids: impl IntoIterator<Item = String>,
|
||||
store: &dyn AttachmentStore,
|
||||
) -> BTreeSet<String> {
|
||||
let mut checks = stream::iter(ids)
|
||||
.map(|id| async move { (!store.is_resolvable(&id).await).then_some(id) })
|
||||
.buffer_unordered(8);
|
||||
let mut missing = BTreeSet::new();
|
||||
// Bound the entire preflight. Responses can still validate unchecked IDs.
|
||||
let _ = tokio::time::timeout(Duration::from_millis(250), async {
|
||||
while let Some(result) = checks.next().await {
|
||||
missing.extend(result);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
missing
|
||||
}
|
||||
|
||||
/// Keep per-item metadata paired with the submitted input when an audio-only
|
||||
/// message disappears. The resulting projection also becomes the checkpoint.
|
||||
pub(crate) fn project_compaction_audio(
|
||||
input: &mut Vec<ResponseItem>,
|
||||
metadata: &mut Vec<Option<CodexHarnessMetadata>>,
|
||||
unavailable: &BTreeSet<String>,
|
||||
) {
|
||||
if unavailable.is_empty() {
|
||||
return;
|
||||
}
|
||||
debug_assert_eq!(input.len(), metadata.len());
|
||||
let mut envelopes = input
|
||||
.drain(..)
|
||||
.zip(metadata.drain(..))
|
||||
.map(|(item, metadata)| ResponseItemEnvelope { item, metadata })
|
||||
.collect();
|
||||
project_file_audio(&mut envelopes, unavailable);
|
||||
for envelope in envelopes {
|
||||
input.push(envelope.item);
|
||||
metadata.push(envelope.metadata);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn project_file_audio(
|
||||
items: &mut Vec<ResponseItemEnvelope>,
|
||||
rejected_file_ids: &BTreeSet<String>,
|
||||
) {
|
||||
items.retain_mut(|envelope| {
|
||||
let ResponseItem::Message {
|
||||
role,
|
||||
content,
|
||||
internal_chat_message_metadata_passthrough,
|
||||
..
|
||||
} = &mut envelope.item
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let keep = content
|
||||
.iter()
|
||||
.map(|part| {
|
||||
!matches!(part, ContentItem::InputAudio {
|
||||
audio: AudioReference::File { file_id },
|
||||
} if rejected_file_ids.contains(file_id))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if keep.iter().all(|keep| *keep) {
|
||||
return true;
|
||||
}
|
||||
retain_aligned(content, &keep);
|
||||
if let Some(metadata) = internal_chat_message_metadata_passthrough {
|
||||
if let Some(kinds) = &mut metadata.content_item_kinds {
|
||||
retain_aligned(kinds, &keep);
|
||||
}
|
||||
if let Some(sources) = &mut metadata.content_item_metadata {
|
||||
retain_aligned(sources, &keep);
|
||||
}
|
||||
}
|
||||
role != "user" || !content.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
fn retain_aligned<T>(items: &mut Vec<T>, keep: &[bool]) {
|
||||
if items.len() != keep.len() {
|
||||
items.clear();
|
||||
return;
|
||||
}
|
||||
let mut index = 0;
|
||||
items.retain(|_| {
|
||||
let retain = keep[index];
|
||||
index += 1;
|
||||
retain
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_rejected_audio_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,239 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::InternalChatMessageMetadataPassthrough;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn file_audio(file_id: &str) -> ContentItem {
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::File {
|
||||
file_id: file_id.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_audio() -> ContentItem {
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/wav;base64,AA==".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn message(content: Vec<ContentItem>) -> ResponseItem {
|
||||
ResponseItem::Message {
|
||||
encrypted_content: None,
|
||||
status: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content,
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_error() -> CodexErrorDetails {
|
||||
CodexErrorDetails::InvalidAudioInput {
|
||||
per_recording: true,
|
||||
message: "invalid recording".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rejected_file_audio_id(error: &CodexErrorDetails, items: &[ResponseItem]) -> Option<String> {
|
||||
SubmittedFileAudio::from_request(items, /*accepted*/ None, std::iter::empty())?
|
||||
.rejected_file_id(error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previously_accepted_file_only_disambiguates_clip_specific_errors() {
|
||||
let mut context = akode_history::RetainedContext::default();
|
||||
let good = message(vec![file_audio("file_a")]);
|
||||
let evidence = pending_audio_confirmation(
|
||||
/*previous*/ None,
|
||||
"turn",
|
||||
"model",
|
||||
"provider",
|
||||
std::slice::from_ref(&good),
|
||||
)
|
||||
.expect("new audio");
|
||||
context.record(
|
||||
&akode_history::RetainedContextEvent::AcceptedFileAudio {
|
||||
evidence: evidence.into(),
|
||||
},
|
||||
&akode_protocol_test_support::uuid_v7_item_id_generator_for_test(),
|
||||
);
|
||||
assert!(
|
||||
context
|
||||
.accepted_file_audio("another model", "provider")
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
context
|
||||
.accepted_file_audio("model", "another provider")
|
||||
.is_none()
|
||||
);
|
||||
let accepted = context.accepted_file_audio("model", "provider");
|
||||
let items = [good, message(vec![file_audio("file_b")])];
|
||||
let candidate = SubmittedFileAudio::from_request(&items, accepted, std::iter::empty())
|
||||
.expect("one new recording");
|
||||
assert!(candidate.matches_rejection(&audio_error()));
|
||||
assert!(
|
||||
!candidate.matches_rejection(&CodexErrorDetails::InvalidAudioInput {
|
||||
message: "The combined audio input is too large.".into(),
|
||||
per_recording: false,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
candidate.rejected_file_id(&audio_error()).as_deref(),
|
||||
Some("file_b")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_output_audio_makes_an_invalid_audio_error_ambiguous() {
|
||||
for kind in ["function_call_output", "custom_tool_call_output"] {
|
||||
let output = serde_json::from_value(serde_json::json!({
|
||||
"type": kind,
|
||||
"call_id": "call",
|
||||
"output": [{"type": "input_audio", "audio_url": "data:audio/wav;base64,AA=="}],
|
||||
}))
|
||||
.expect("valid tool output");
|
||||
let items = [message(vec![file_audio("valid_upload")]), output];
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(&audio_error(), &items),
|
||||
None,
|
||||
"{kind}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_audio_error_only_to_one_visible_file_audio() {
|
||||
let error = audio_error();
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(&error, &[message(vec![file_audio("file_a")])]),
|
||||
Some("file_a".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(
|
||||
&error,
|
||||
&[message(vec![file_audio("file_a"), file_audio("file_b")])]
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(
|
||||
&error,
|
||||
&[message(vec![file_audio("file_a"), inline_audio()])]
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(
|
||||
&error,
|
||||
&[
|
||||
message(vec![file_audio("file_a")]),
|
||||
ResponseItem::ContextCompaction {
|
||||
id: None,
|
||||
encrypted_content: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
]
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_file_error_counts_the_submitted_projection_not_raw_history() {
|
||||
let error = CodexErrorDetails::UnexpectedStatus(akode_protocol::error::UnexpectedResponseError {
|
||||
status: http::StatusCode::NOT_FOUND,
|
||||
body: serde_json::json!({"error": {"message": "Invalid input: Unknown `file_id` in input content."}}).to_string(),
|
||||
url: None,
|
||||
user_message: None,
|
||||
cf_ray: None,
|
||||
request_id: None,
|
||||
identity_authorization_error: None,
|
||||
identity_error_code: None,
|
||||
});
|
||||
let unavailable_image_projection = message(vec![
|
||||
ContentItem::InputText {
|
||||
text: "[Image unavailable]".to_string(),
|
||||
},
|
||||
file_audio("file_audio"),
|
||||
]);
|
||||
assert_eq!(
|
||||
rejected_file_audio_id(&error, &[unavailable_image_projection]),
|
||||
Some("file_audio".to_string())
|
||||
);
|
||||
let unresolved_image = message(vec![
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_image".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
file_audio("file_audio"),
|
||||
]);
|
||||
assert_eq!(rejected_file_audio_id(&error, &[unresolved_image]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_removes_only_rejected_audio_and_keeps_metadata_aligned() {
|
||||
let mut first = message(vec![
|
||||
ContentItem::InputText {
|
||||
text: "first".to_string(),
|
||||
},
|
||||
file_audio("file_a"),
|
||||
]);
|
||||
let ResponseItem::Message {
|
||||
internal_chat_message_metadata_passthrough,
|
||||
..
|
||||
} = &mut first
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
*internal_chat_message_metadata_passthrough = Some(InternalChatMessageMetadataPassthrough {
|
||||
content_item_kinds: Some(vec![
|
||||
ContentItemKind("user.text".to_string()),
|
||||
ContentItemKind("user.audio".to_string()),
|
||||
]),
|
||||
..Default::default()
|
||||
});
|
||||
let second = message(vec![file_audio("file_b")]);
|
||||
let rejected_only = message(vec![file_audio("file_a")]);
|
||||
let raw = vec![first, second.clone(), rejected_only];
|
||||
let mut projected = raw
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.collect();
|
||||
project_file_audio(&mut projected, &BTreeSet::from(["file_a".to_string()]));
|
||||
let projected = projected
|
||||
.into_iter()
|
||||
.map(ResponseItemEnvelope::into_item)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let ResponseItem::Message {
|
||||
content,
|
||||
internal_chat_message_metadata_passthrough: Some(metadata),
|
||||
..
|
||||
} = &projected[0]
|
||||
else {
|
||||
panic!("expected retained first message")
|
||||
};
|
||||
assert_eq!(
|
||||
content,
|
||||
&[ContentItem::InputText {
|
||||
text: "first".to_string()
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
metadata.content_item_kinds,
|
||||
Some(vec![ContentItemKind("user.text".to_string())])
|
||||
);
|
||||
assert_eq!(projected[1], second);
|
||||
assert_eq!(projected.len(), 2);
|
||||
assert_eq!(raw.len(), 3, "the retained history was not rewritten");
|
||||
}
|
||||
4012
akode-rs/core/src/context_manager/history_tests.rs
Normal file
4012
akode-rs/core/src/context_manager/history_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
222
akode-rs/core/src/context_manager/history_user_authorization.rs
Normal file
222
akode-rs/core/src/context_manager/history_user_authorization.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
//! Captures original user/assistant exchanges and adopts copied context when a worker becomes a root.
|
||||
//! Inherited history remains excluded for workers; roots also recover it from checkpoints.
|
||||
//! Oversized originals retain bounded, incomplete excerpts for root review.
|
||||
//! Checkpoint copies cannot establish original completeness, even when their text is short.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::ContextManager;
|
||||
use crate::compact::is_summary_message;
|
||||
use crate::context::UserGoalUpdate;
|
||||
use crate::context::is_contextual_user_fragment;
|
||||
use crate::event_mapping::parse_turn_item;
|
||||
use crate::guardian::GUARDIAN_MAX_ROOT_MESSAGE_TOKENS;
|
||||
use crate::guardian::guardian_truncate_text;
|
||||
use akode_history::CodexHarnessMetadata;
|
||||
use akode_history::ReconciledRetainedContext;
|
||||
use akode_history::RetainedContext;
|
||||
use akode_history::RetainedInputSource;
|
||||
use akode_history::RetainedUserMessage;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
|
||||
/// Checkpoint items may have been shortened while preserving their original metadata.
|
||||
pub(super) enum RetainedMessageSource {
|
||||
Original,
|
||||
Checkpoint,
|
||||
}
|
||||
|
||||
impl ContextManager {
|
||||
pub(super) fn has_legacy_user_messages(&self) -> bool {
|
||||
ReconciledRetainedContext::new(Some(&self.retained_context), std::iter::empty())
|
||||
.unmatched_user_messages(self.legacy_user_messages())
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Bounded instruction candidates from the legacy backup; their ordering is unknown.
|
||||
pub(crate) fn legacy_user_messages(&self) -> impl Iterator<Item = RetainedUserMessage> + '_ {
|
||||
self.original_legacy_user_messages().map(|mut message| {
|
||||
message.text =
|
||||
guardian_truncate_text(&message.text, GUARDIAN_MAX_ROOT_MESSAGE_TOKENS).0;
|
||||
message
|
||||
})
|
||||
}
|
||||
|
||||
/// Original legacy candidates for request preparation; storage remains independently bounded.
|
||||
pub(crate) fn original_legacy_user_messages(
|
||||
&self,
|
||||
) -> impl Iterator<Item = RetainedUserMessage> + '_ {
|
||||
self.guardian_history_items()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(move |item| {
|
||||
if !crate::context::is_user_authorization_message(item) {
|
||||
return None;
|
||||
}
|
||||
let Some(TurnItem::UserMessage(message)) = parse_turn_item(item) else {
|
||||
return None;
|
||||
};
|
||||
let text = message.message();
|
||||
if is_summary_message(&text)
|
||||
|| text.trim_start().starts_with("<user_action>")
|
||||
|| is_contextual_user_fragment(&ContentItem::InputText { text: text.clone() })
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(RetainedUserMessage {
|
||||
phase: None,
|
||||
origin: akode_history::UserInputOrigin::from_message(item),
|
||||
turn_id: item.turn_id().unwrap_or_default().to_owned(),
|
||||
message_id: item.id().map(|id| id.as_str().to_owned()),
|
||||
text,
|
||||
complete: false,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn restore_retained_context(&mut self, checkpoint: Option<&RetainedContext>) {
|
||||
Arc::make_mut(&mut self.retained_context).restore(checkpoint, &self.items);
|
||||
let items = Arc::clone(&self.items);
|
||||
for envelope in items.iter().filter(|envelope| {
|
||||
envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.is_some_and(|metadata| metadata.delivered_assistant_message.is_some())
|
||||
}) {
|
||||
let _ = self.record_retained_message(
|
||||
&envelope.item,
|
||||
envelope.metadata.as_ref(),
|
||||
RetainedMessageSource::Checkpoint,
|
||||
);
|
||||
}
|
||||
if self.retain_inherited_user_messages
|
||||
&& !self.retained_context.has_inherited_user_messages()
|
||||
{
|
||||
// Worker checkpoints intentionally omit copied instructions. A standalone
|
||||
// root adopts the surviving prefix without duplicating an adopted checkpoint.
|
||||
let items = Arc::clone(&self.items);
|
||||
for envelope in items.iter().filter(|envelope| {
|
||||
envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.is_some_and(|metadata| metadata.inherited_user_message)
|
||||
}) {
|
||||
let _ = self.record_retained_message(
|
||||
&envelope.item,
|
||||
envelope.metadata.as_ref(),
|
||||
RetainedMessageSource::Checkpoint,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_retained_message(
|
||||
&mut self,
|
||||
item: &ResponseItem,
|
||||
metadata: Option<&CodexHarnessMetadata>,
|
||||
source: RetainedMessageSource,
|
||||
) -> Option<akode_history::RetainedSource> {
|
||||
if let Some(text) =
|
||||
metadata.and_then(|metadata| metadata.delivered_assistant_message.as_ref())
|
||||
&& let ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} = item
|
||||
{
|
||||
let call = self.items.iter().rev().find(|envelope| {
|
||||
matches!(&envelope.item, ResponseItem::FunctionCall { call_id: id, .. } if id == call_id)
|
||||
})?;
|
||||
let source = RetainedInputSource::from(call.metadata.as_ref());
|
||||
if source == RetainedInputSource::Inherited && !self.retain_inherited_user_messages {
|
||||
return None;
|
||||
}
|
||||
// The host captured this bounded text before post-tool hooks. The output
|
||||
// may be rejected, aborted, or truncated; retain the confirmed text at
|
||||
// the original call's position, not at its later completion position.
|
||||
Arc::make_mut(&mut self.retained_context).record_assistant_message(
|
||||
RetainedUserMessage {
|
||||
phase: None,
|
||||
origin: akode_history::UserInputOrigin::User,
|
||||
turn_id: call.item.turn_id().unwrap_or_default().to_owned(),
|
||||
message_id: call.item.id().map(|id| id.as_str().to_owned()),
|
||||
text: text.clone(),
|
||||
complete: true,
|
||||
},
|
||||
source,
|
||||
&self.item_id_generator,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let is_assistant =
|
||||
matches!(item, ResponseItem::Message { role, .. } if role == "assistant");
|
||||
if metadata.is_some_and(|metadata| metadata.compaction_output)
|
||||
|| (!is_assistant && !crate::context::is_user_authorization_message(item))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut captured = None;
|
||||
let inherited = metadata.is_some_and(|metadata| metadata.inherited_user_message);
|
||||
if (!inherited || self.retain_inherited_user_messages)
|
||||
&& let ResponseItem::Message {
|
||||
content,
|
||||
phase,
|
||||
internal_chat_message_metadata_passthrough,
|
||||
..
|
||||
} = item
|
||||
{
|
||||
let mut complete = matches!(source, RetainedMessageSource::Original)
|
||||
&& (is_assistant
|
||||
|| internal_chat_message_metadata_passthrough
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.content_item_kinds.as_ref())
|
||||
.is_some_and(|kinds| {
|
||||
kinds.len() == content.len()
|
||||
&& kinds.iter().all(|kind| {
|
||||
kind.0.starts_with("user.")
|
||||
&& kind.0 != UserGoalUpdate::OMITTED_OBJECTIVE_KIND
|
||||
})
|
||||
}));
|
||||
complete &= metadata
|
||||
.and_then(|metadata| metadata.retained_source.as_ref())
|
||||
.is_none_or(|source| source.complete);
|
||||
let text = content
|
||||
.iter()
|
||||
.filter_map(|content| match content {
|
||||
ContentItem::InputText { text } | ContentItem::OutputText { text, .. } => {
|
||||
Some(text.as_str())
|
||||
}
|
||||
_ => {
|
||||
complete = false;
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
// Keep the same bounded text that child reviewers receive before
|
||||
// compaction, instead of letting storage discard a large source.
|
||||
// Local instruction sections still omit incomplete originals whole.
|
||||
let (text, truncated) = guardian_truncate_text(&text, GUARDIAN_MAX_ROOT_MESSAGE_TOKENS);
|
||||
complete &= !truncated;
|
||||
let message = RetainedUserMessage {
|
||||
phase: phase.clone(),
|
||||
origin: akode_history::UserInputOrigin::from_message(item),
|
||||
turn_id: item.turn_id().unwrap_or_default().to_owned(),
|
||||
message_id: item.id().map(|id| id.as_str().to_owned()),
|
||||
text,
|
||||
complete,
|
||||
};
|
||||
let retained = Arc::make_mut(&mut self.retained_context);
|
||||
captured = if is_assistant {
|
||||
retained.record_assistant_message(message, metadata.into(), &self.item_id_generator)
|
||||
} else {
|
||||
retained.record_user_message(message, metadata.into(), &self.item_id_generator)
|
||||
};
|
||||
}
|
||||
if !is_assistant {
|
||||
self.user_message_revision = self.user_message_revision.saturating_add(1);
|
||||
}
|
||||
captured
|
||||
}
|
||||
}
|
||||
122
akode-rs/core/src/context_manager/image_availability.rs
Normal file
122
akode-rs/core/src/context_manager/image_availability.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Projects unavailable file images into placeholders without changing tool attribution.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use akode_attachment_store::AttachmentStore;
|
||||
use akode_context_fragments::AnnotatedContent;
|
||||
use akode_context_fragments::set_annotated_content;
|
||||
use akode_context_fragments::to_annotated_content;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::ContentItemMetadata;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::ImageReference;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use futures::StreamExt;
|
||||
use futures::stream;
|
||||
|
||||
const MAX_CONCURRENT_IMAGE_AVAILABILITY_CHECKS: usize = 8;
|
||||
|
||||
/// Checks distinct file IDs concurrently and replaces only unavailable image content.
|
||||
pub(crate) async fn replace_unresolvable_image_files<'a>(
|
||||
items: impl Iterator<Item = &'a mut ResponseItem>,
|
||||
image_store: &dyn AttachmentStore,
|
||||
) {
|
||||
let items: Vec<_> = items.collect();
|
||||
let mut file_ids = HashSet::new();
|
||||
for item in &items {
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
for part in content {
|
||||
if let ContentItem::InputImage {
|
||||
image: ImageReference::File { file_id },
|
||||
..
|
||||
} = part
|
||||
{
|
||||
file_ids.insert(file_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(content) = output.content_items() {
|
||||
for part in content {
|
||||
if let FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File { file_id },
|
||||
..
|
||||
} = part
|
||||
{
|
||||
file_ids.insert(file_id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut checks = stream::iter(file_ids)
|
||||
.map(|file_id| async move {
|
||||
let resolvable = image_store.is_resolvable(&file_id).await;
|
||||
(file_id, resolvable)
|
||||
})
|
||||
.buffer_unordered(MAX_CONCURRENT_IMAGE_AVAILABILITY_CHECKS);
|
||||
let mut unavailable_file_ids = HashSet::new();
|
||||
while let Some((file_id, resolvable)) = checks.next().await {
|
||||
if !resolvable {
|
||||
unavailable_file_ids.insert(file_id);
|
||||
}
|
||||
}
|
||||
if unavailable_file_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for item in items {
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => {
|
||||
let mut unavailable = Vec::new();
|
||||
for (index, part) in content.iter().enumerate() {
|
||||
if let ContentItem::InputImage {
|
||||
image: ImageReference::File { file_id },
|
||||
..
|
||||
} = part
|
||||
&& unavailable_file_ids.contains(file_id)
|
||||
{
|
||||
unavailable.push(index);
|
||||
}
|
||||
}
|
||||
if unavailable.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(mut content) = to_annotated_content(item) else {
|
||||
continue;
|
||||
};
|
||||
for index in unavailable {
|
||||
content[index] = AnnotatedContent::text(
|
||||
"[image unavailable]",
|
||||
ContentItemKind("images.unavailable".to_string()),
|
||||
ContentItemMetadata::harness(),
|
||||
);
|
||||
}
|
||||
let _ = set_annotated_content(item, content);
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(content) = output.content_items_mut() {
|
||||
for part in content {
|
||||
if let FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File { file_id },
|
||||
..
|
||||
} = part
|
||||
&& unavailable_file_ids.contains(file_id)
|
||||
{
|
||||
*part = FunctionCallOutputContentItem::InputText {
|
||||
text: "[image unavailable]".to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
akode-rs/core/src/context_manager/mod.rs
Normal file
15
akode-rs/core/src/context_manager/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
mod history;
|
||||
mod image_availability;
|
||||
mod normalize;
|
||||
mod sampling;
|
||||
pub(crate) mod updates;
|
||||
|
||||
pub(crate) use history::ContextManager;
|
||||
pub(crate) use history::HistoryReplacement;
|
||||
pub(crate) use history::estimate_image_reference_bytes;
|
||||
pub(crate) use history::estimate_item_token_count;
|
||||
pub(crate) use history::estimate_item_token_count_with_audio;
|
||||
pub(crate) use history::is_user_turn_boundary;
|
||||
pub(crate) use history::rejected_audio;
|
||||
pub(crate) use image_availability::replace_unresolvable_image_files;
|
||||
pub(crate) use sampling::sampled_through;
|
||||
431
akode-rs/core/src/context_manager/normalize.rs
Normal file
431
akode-rs/core/src/context_manager/normalize.rs
Normal file
@@ -0,0 +1,431 @@
|
||||
use akode_context_fragments::set_annotated_content;
|
||||
use akode_context_fragments::to_annotated_content;
|
||||
use akode_history::ResponseItemEnvelope;
|
||||
use akode_protocol::ResponseItemId;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::openai_models::InputModality;
|
||||
use std::collections::HashSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::UnsupportedMedia;
|
||||
use crate::util::error_or_panic;
|
||||
use tracing::info;
|
||||
|
||||
// Changing this value would change model-visible IDs and invalidate prompt caches.
|
||||
const SYNTHETIC_OUTPUT_ID_NAMESPACE: Uuid = Uuid::from_u128(0x90d38d3e_6a5b_4d52_bfe2_2f1e634bfac4);
|
||||
|
||||
pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItemEnvelope>) {
|
||||
let mut function_output_ids = HashSet::new();
|
||||
let mut tool_search_output_ids = HashSet::new();
|
||||
let mut custom_tool_output_ids = HashSet::new();
|
||||
for envelope in items.iter() {
|
||||
match &envelope.item {
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
function_output_ids.insert(call_id.as_str());
|
||||
}
|
||||
ResponseItem::ToolSearchOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
tool_search_output_ids.insert(call_id.as_str());
|
||||
}
|
||||
ResponseItem::CustomToolCallOutput { call_id, .. } => {
|
||||
custom_tool_output_ids.insert(call_id.as_str());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Collect synthetic outputs to insert immediately after their calls.
|
||||
// Store the insertion position (index of call) alongside the item so
|
||||
// we can insert in reverse order and avoid index shifting.
|
||||
let mut missing_outputs_to_insert: Vec<(usize, ResponseItemEnvelope)> = Vec::new();
|
||||
|
||||
for (idx, envelope) in items.iter().enumerate() {
|
||||
match &envelope.item {
|
||||
ResponseItem::FunctionCall { id, call_id, .. }
|
||||
if !function_output_ids.contains(call_id.as_str()) =>
|
||||
{
|
||||
info!("Function call output is missing for call id: {call_id}");
|
||||
missing_outputs_to_insert.push((
|
||||
idx,
|
||||
ResponseItemEnvelope::new(ResponseItem::FunctionCallOutput {
|
||||
id: synthetic_output_id("fco", id.as_deref()),
|
||||
call_id: Some(call_id.clone()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
ResponseItem::ToolSearchCall {
|
||||
id,
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} if !tool_search_output_ids.contains(call_id.as_str()) => {
|
||||
info!("Tool search output is missing for call id: {call_id}");
|
||||
missing_outputs_to_insert.push((
|
||||
idx,
|
||||
ResponseItemEnvelope::new(ResponseItem::ToolSearchOutput {
|
||||
id: synthetic_output_id("tso", id.as_deref()),
|
||||
call_id: Some(call_id.clone()),
|
||||
status: "completed".to_string(),
|
||||
execution: "client".to_string(),
|
||||
tools: Vec::new(),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
ResponseItem::CustomToolCall { id, call_id, .. }
|
||||
if !custom_tool_output_ids.contains(call_id.as_str()) =>
|
||||
{
|
||||
// Preserved-prefix forks mark copied calls as inherited. A call still
|
||||
// running in the parent has no output in the child's snapshot.
|
||||
if !envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.is_some_and(|metadata| metadata.inherited_user_message)
|
||||
{
|
||||
error_or_panic(format!(
|
||||
"Custom tool call output is missing for call id: {call_id}"
|
||||
));
|
||||
}
|
||||
missing_outputs_to_insert.push((
|
||||
idx,
|
||||
ResponseItemEnvelope::new(ResponseItem::CustomToolCallOutput {
|
||||
id: synthetic_output_id("ctco", id.as_deref()),
|
||||
call_id: call_id.clone(),
|
||||
name: None,
|
||||
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
// LocalShellCall is represented in upstream streams by a FunctionCallOutput
|
||||
ResponseItem::LocalShellCall {
|
||||
id,
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} if !function_output_ids.contains(call_id.as_str()) => {
|
||||
// Preserved-prefix forks mark copied calls as inherited. A call still
|
||||
// running in the parent has no output in the child's snapshot.
|
||||
if !envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.is_some_and(|metadata| metadata.inherited_user_message)
|
||||
{
|
||||
error_or_panic(format!(
|
||||
"Local shell call output is missing for call id: {call_id}"
|
||||
));
|
||||
}
|
||||
missing_outputs_to_insert.push((
|
||||
idx,
|
||||
ResponseItemEnvelope::new(ResponseItem::FunctionCallOutput {
|
||||
id: synthetic_output_id("fco", id.as_deref()),
|
||||
call_id: Some(call_id.clone()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
drop((
|
||||
function_output_ids,
|
||||
tool_search_output_ids,
|
||||
custom_tool_output_ids,
|
||||
));
|
||||
|
||||
// Insert synthetic outputs in reverse index order to avoid re-indexing.
|
||||
for (idx, output_item) in missing_outputs_to_insert.into_iter().rev() {
|
||||
items.insert(idx + 1, output_item);
|
||||
}
|
||||
}
|
||||
|
||||
/// Derives a stable ID for a prompt-only output from its source call's item ID.
|
||||
///
|
||||
/// Prompt normalization can run repeatedly without persisting its synthetic
|
||||
/// outputs, so the namespace and name format must remain stable across retries
|
||||
/// and resumes to preserve prompt-cache reuse. Returning `None` when the source
|
||||
/// call has no ID preserves the legacy behavior for older history items.
|
||||
fn synthetic_output_id(prefix: &str, item_id: Option<&str>) -> Option<ResponseItemId> {
|
||||
let source_id = item_id.filter(|id| !id.is_empty())?;
|
||||
let name = format!("{prefix}:{source_id}");
|
||||
Some(ResponseItemId::with_suffix(
|
||||
prefix,
|
||||
Uuid::new_v5(&SYNTHETIC_OUTPUT_ID_NAMESPACE, name.as_bytes()),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn remove_orphan_outputs(items: &mut Vec<ResponseItemEnvelope>) {
|
||||
let mut function_call_ids = HashSet::new();
|
||||
let mut tool_search_call_ids = HashSet::new();
|
||||
let mut custom_tool_call_ids = HashSet::new();
|
||||
for envelope in items.iter() {
|
||||
match &envelope.item {
|
||||
ResponseItem::FunctionCall { call_id, .. }
|
||||
| ResponseItem::LocalShellCall {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
function_call_ids.insert(call_id.as_str());
|
||||
}
|
||||
ResponseItem::ToolSearchCall {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
tool_search_call_ids.insert(call_id.as_str());
|
||||
}
|
||||
ResponseItem::CustomToolCall { call_id, .. } => {
|
||||
custom_tool_call_ids.insert(call_id.as_str());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let mut orphan_positions = Vec::new();
|
||||
for (position, envelope) in items.iter().enumerate() {
|
||||
match &envelope.item {
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} if !function_call_ids.contains(call_id.as_str()) => {
|
||||
error_or_panic(format!(
|
||||
"Orphan function call output for call id: {call_id}"
|
||||
));
|
||||
orphan_positions.push(position);
|
||||
}
|
||||
ResponseItem::CustomToolCallOutput { call_id, .. }
|
||||
if !custom_tool_call_ids.contains(call_id.as_str()) =>
|
||||
{
|
||||
error_or_panic(format!(
|
||||
"Orphan custom tool call output for call id: {call_id}"
|
||||
));
|
||||
orphan_positions.push(position);
|
||||
}
|
||||
ResponseItem::ToolSearchOutput {
|
||||
call_id: Some(call_id),
|
||||
execution,
|
||||
..
|
||||
} if execution != "server" && !tool_search_call_ids.contains(call_id.as_str()) => {
|
||||
error_or_panic(format!("Orphan tool search output for call id: {call_id}"));
|
||||
orphan_positions.push(position);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !orphan_positions.is_empty() {
|
||||
let mut orphan_positions = orphan_positions.into_iter().peekable();
|
||||
let mut position = 0;
|
||||
items.retain(|_| {
|
||||
let retain = orphan_positions.peek() != Some(&position);
|
||||
if !retain {
|
||||
orphan_positions.next();
|
||||
}
|
||||
position += 1;
|
||||
retain
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove_corresponding_for(items: &mut Vec<ResponseItemEnvelope>, item: &ResponseItem) {
|
||||
match item {
|
||||
ResponseItem::FunctionCall { call_id, .. } => {
|
||||
remove_first_matching(items, |i| {
|
||||
matches!(
|
||||
i,
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(existing),
|
||||
..
|
||||
} if existing == call_id
|
||||
)
|
||||
});
|
||||
}
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
if let Some(pos) = items.iter().position(|envelope| {
|
||||
matches!(&envelope.item, ResponseItem::FunctionCall { call_id: existing, .. } if existing == call_id)
|
||||
}) {
|
||||
items.remove(pos);
|
||||
} else if let Some(pos) = items.iter().position(|envelope| {
|
||||
matches!(&envelope.item, ResponseItem::LocalShellCall { call_id: Some(existing), .. } if existing == call_id)
|
||||
}) {
|
||||
items.remove(pos);
|
||||
}
|
||||
}
|
||||
ResponseItem::ToolSearchCall {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
remove_first_matching(items, |i| {
|
||||
matches!(
|
||||
i,
|
||||
ResponseItem::ToolSearchOutput {
|
||||
call_id: Some(existing),
|
||||
..
|
||||
} if existing == call_id
|
||||
)
|
||||
});
|
||||
}
|
||||
ResponseItem::ToolSearchOutput {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
remove_first_matching(
|
||||
items,
|
||||
|i| {
|
||||
matches!(
|
||||
i,
|
||||
ResponseItem::ToolSearchCall {
|
||||
call_id: Some(existing),
|
||||
..
|
||||
} if existing == call_id
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
ResponseItem::CustomToolCall { call_id, .. } => {
|
||||
remove_first_matching(items, |i| {
|
||||
matches!(
|
||||
i,
|
||||
ResponseItem::CustomToolCallOutput {
|
||||
call_id: existing, ..
|
||||
} if existing == call_id
|
||||
)
|
||||
});
|
||||
}
|
||||
ResponseItem::CustomToolCallOutput { call_id, .. } => {
|
||||
remove_first_matching(
|
||||
items,
|
||||
|i| matches!(i, ResponseItem::CustomToolCall { call_id: existing, .. } if existing == call_id),
|
||||
);
|
||||
}
|
||||
ResponseItem::LocalShellCall {
|
||||
call_id: Some(call_id),
|
||||
..
|
||||
} => {
|
||||
remove_first_matching(items, |i| {
|
||||
matches!(
|
||||
i,
|
||||
ResponseItem::FunctionCallOutput {
|
||||
call_id: Some(existing),
|
||||
..
|
||||
} if existing == call_id
|
||||
)
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_first_matching<F>(items: &mut Vec<ResponseItemEnvelope>, predicate: F)
|
||||
where
|
||||
F: Fn(&ResponseItem) -> bool,
|
||||
{
|
||||
if let Some(pos) = items.iter().position(|envelope| predicate(&envelope.item)) {
|
||||
items.remove(pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip image content from messages and tool outputs when the model does not support images.
|
||||
/// When `input_modalities` contains `InputModality::Image`, no stripping is performed.
|
||||
pub(crate) fn strip_images_when_unsupported(
|
||||
input_modalities: &[InputModality],
|
||||
items: &mut [ResponseItemEnvelope],
|
||||
) {
|
||||
let supports_images = input_modalities.contains(&InputModality::Image);
|
||||
if supports_images {
|
||||
return;
|
||||
}
|
||||
|
||||
for envelope in items.iter_mut() {
|
||||
match &mut envelope.item {
|
||||
ResponseItem::Message { .. } => {
|
||||
let Some(mut content) = to_annotated_content(&mut envelope.item) else {
|
||||
continue;
|
||||
};
|
||||
for content_item in &mut content {
|
||||
if matches!(content_item.content(), ContentItem::InputImage { .. }) {
|
||||
*content_item = UnsupportedMedia::IMAGE.render_fragment().into_parts().1;
|
||||
}
|
||||
}
|
||||
let _ = set_annotated_content(&mut envelope.item, content);
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(content_items) = output.content_items_mut() {
|
||||
let mut normalized_content_items = Vec::with_capacity(content_items.len());
|
||||
for content_item in content_items.iter() {
|
||||
match content_item {
|
||||
FunctionCallOutputContentItem::InputImage { .. } => {
|
||||
normalized_content_items
|
||||
.push(UnsupportedMedia::IMAGE.render().into());
|
||||
}
|
||||
_ => normalized_content_items.push(content_item.clone()),
|
||||
}
|
||||
}
|
||||
*content_items = normalized_content_items;
|
||||
}
|
||||
}
|
||||
ResponseItem::ImageGenerationCall { result, .. } => {
|
||||
result.clear();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip audio content from messages and tool outputs when the model does not support audio.
|
||||
/// When `input_modalities` contains `InputModality::Audio`, no stripping is performed.
|
||||
pub(crate) fn strip_audio_when_unsupported(
|
||||
input_modalities: &[InputModality],
|
||||
items: &mut [ResponseItemEnvelope],
|
||||
) {
|
||||
if input_modalities.contains(&InputModality::Audio) {
|
||||
return;
|
||||
}
|
||||
|
||||
for envelope in items.iter_mut() {
|
||||
match &mut envelope.item {
|
||||
ResponseItem::Message { .. } => {
|
||||
let Some(mut content) = to_annotated_content(&mut envelope.item) else {
|
||||
continue;
|
||||
};
|
||||
for content_item in &mut content {
|
||||
if matches!(content_item.content(), ContentItem::InputAudio { .. }) {
|
||||
*content_item = UnsupportedMedia::AUDIO.render_fragment().into_parts().1;
|
||||
}
|
||||
}
|
||||
let _ = set_annotated_content(&mut envelope.item, content);
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(content_items) = output.content_items_mut() {
|
||||
for content_item in content_items.iter_mut() {
|
||||
if matches!(
|
||||
content_item,
|
||||
FunctionCallOutputContentItem::InputAudio { .. }
|
||||
) {
|
||||
*content_item = UnsupportedMedia::AUDIO.render().into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
76
akode-rs/core/src/context_manager/sampling.rs
Normal file
76
akode-rs/core/src/context_manager/sampling.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
//! Tracks the prefix included in normal inference, independently of later history appends.
|
||||
//! These checkpoints are harness metadata; compaction and replay never acknowledge new input.
|
||||
|
||||
use akode_history::ResponseItemEnvelope;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(super) struct SamplingProgress {
|
||||
pub(super) last_sequence: u64,
|
||||
sampled_through: u64,
|
||||
}
|
||||
|
||||
impl SamplingProgress {
|
||||
pub(super) fn record(&mut self, envelope: &mut ResponseItemEnvelope) {
|
||||
let metadata = envelope.metadata.get_or_insert_default();
|
||||
let sequence = metadata
|
||||
.history_sequence
|
||||
.get_or_insert_with(|| self.last_sequence.strict_add(/* rhs */ 1));
|
||||
self.last_sequence = self.last_sequence.max(*sequence);
|
||||
self.sampled_through = self
|
||||
.sampled_through
|
||||
.max(metadata.sampled_through_sequence.unwrap_or_default());
|
||||
metadata.sampled_through_sequence = Some(self.sampled_through);
|
||||
}
|
||||
|
||||
pub(super) fn restore(items: &mut [ResponseItemEnvelope]) -> Self {
|
||||
let mut progress = Self::default();
|
||||
for metadata in items.iter().filter_map(|item| item.metadata.as_ref()) {
|
||||
progress.last_sequence = progress
|
||||
.last_sequence
|
||||
.max(metadata.history_sequence.unwrap_or_default());
|
||||
progress.sampled_through = progress
|
||||
.sampled_through
|
||||
.max(metadata.sampled_through_sequence.unwrap_or_default());
|
||||
}
|
||||
progress.last_sequence = progress.last_sequence.max(progress.sampled_through);
|
||||
// Legacy inputs have no delivery proof. Give them distinct identities and keep
|
||||
// them pending until a normal request includes them; never guess from output order.
|
||||
progress.assign_missing_sequences(items);
|
||||
progress
|
||||
}
|
||||
|
||||
pub(super) fn checkpoint(&mut self, items: &mut [ResponseItemEnvelope]) {
|
||||
self.assign_missing_sequences(items);
|
||||
if let Some(first) = items.first_mut() {
|
||||
first
|
||||
.metadata
|
||||
.get_or_insert_default()
|
||||
.sampled_through_sequence = Some(self.sampled_through);
|
||||
}
|
||||
}
|
||||
|
||||
fn assign_missing_sequences(&mut self, items: &mut [ResponseItemEnvelope]) {
|
||||
for envelope in items {
|
||||
if envelope
|
||||
.metadata
|
||||
.as_ref()
|
||||
.and_then(|m| m.history_sequence)
|
||||
.is_none()
|
||||
{
|
||||
self.record(envelope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sampled_through(items: &[ResponseItemEnvelope]) -> u64 {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
item.metadata
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.sampled_through_sequence)
|
||||
})
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
52
akode-rs/core/src/context_manager/updates.rs
Normal file
52
akode-rs/core/src/context_manager/updates.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
//! Groups contextual fragments without moving them across explicit response items.
|
||||
|
||||
use crate::context::world_state::Placement;
|
||||
use crate::context::world_state::WorldStateUpdate;
|
||||
use akode_context_fragments::RenderedFragment;
|
||||
use akode_context_fragments::message_from_parts;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
|
||||
pub(crate) fn build_rendered_message(fragments: Vec<RenderedFragment>) -> Option<ResponseItem> {
|
||||
let role = fragments.first()?.role();
|
||||
debug_assert!(fragments.iter().all(|fragment| fragment.role() == role));
|
||||
let content = fragments
|
||||
.into_iter()
|
||||
.map(|fragment| fragment.into_parts().1)
|
||||
.collect();
|
||||
|
||||
Some(message_from_parts(role, content))
|
||||
}
|
||||
|
||||
pub(crate) fn merge_world_state_updates(updates: Vec<WorldStateUpdate>) -> Vec<ResponseItem> {
|
||||
let mut items = Vec::new();
|
||||
let mut pending = Vec::<RenderedFragment>::new();
|
||||
for update in updates {
|
||||
let fragment = match update.content.into_fragment() {
|
||||
Ok(fragment) => fragment,
|
||||
Err(item) => {
|
||||
items.extend(build_rendered_message(std::mem::take(&mut pending)));
|
||||
items.push(*item);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let rendered = fragment.render_fragment();
|
||||
if update.placement != Placement::Mergeable {
|
||||
items.extend(build_rendered_message(std::mem::take(&mut pending)));
|
||||
items.extend(build_rendered_message(vec![rendered]));
|
||||
continue;
|
||||
}
|
||||
if pending
|
||||
.first()
|
||||
.is_some_and(|previous| previous.role() != rendered.role())
|
||||
{
|
||||
items.extend(build_rendered_message(std::mem::take(&mut pending)));
|
||||
}
|
||||
pending.push(rendered);
|
||||
}
|
||||
items.extend(build_rendered_message(pending));
|
||||
items
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "updates_tests.rs"]
|
||||
mod tests;
|
||||
124
akode-rs/core/src/context_manager/updates_tests.rs
Normal file
124
akode-rs/core/src/context_manager/updates_tests.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
//! Verifies message grouping around explicit world-state response items.
|
||||
|
||||
use super::*;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::world_state::WorldStateUpdateContent;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::InternalChatMessageMetadataPassthrough;
|
||||
use akode_protocol::models::input_text;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct TestFragment {
|
||||
role: &'static str,
|
||||
text: &'static str,
|
||||
markers: (&'static str, &'static str),
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for TestFragment {
|
||||
fn role(&self) -> &'static str {
|
||||
self.role
|
||||
}
|
||||
|
||||
fn content_kind(&self) -> ContentItemKind {
|
||||
ContentItemKind("test.context".to_string())
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
self.markers
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("", "")
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
input_text(self.text.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn fragment(role: &'static str, text: &'static str) -> TestFragment {
|
||||
TestFragment {
|
||||
role,
|
||||
text,
|
||||
markers: ("", ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn message(role: &str, texts: &[&str]) -> ResponseItem {
|
||||
let provenance = serde_json::from_value(json!({"harness_injected": true})).unwrap();
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: role.to_string(),
|
||||
content: texts
|
||||
.iter()
|
||||
.map(|text| ContentItem::InputText {
|
||||
text: text.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: Some(InternalChatMessageMetadataPassthrough {
|
||||
content_item_metadata: Some(vec![provenance; texts.len()]),
|
||||
content_item_kinds: Some(
|
||||
texts
|
||||
.iter()
|
||||
.map(|_| ContentItemKind("test.context".to_string()))
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn additional_tools() -> ResponseItem {
|
||||
ResponseItem::AdditionalTools {
|
||||
id: None,
|
||||
role: "developer".to_string(),
|
||||
tools: Arc::from([json!({"type": "function", "name": "lookup", "parameters": {}})]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updates_preserve_item_boundaries_roles_and_standalone_fragments() {
|
||||
let tools = additional_tools();
|
||||
let updates = vec![
|
||||
WorldStateUpdate::fragment(fragment("developer", "before one")),
|
||||
WorldStateUpdate::fragment(fragment("developer", "before two")),
|
||||
WorldStateUpdate {
|
||||
placement: Placement::Prefix,
|
||||
..WorldStateUpdate::fragment(fragment("developer", "prefix"))
|
||||
},
|
||||
WorldStateUpdate::fragment(fragment("developer", "after prefix")),
|
||||
WorldStateUpdate {
|
||||
placement: Placement::Prefix,
|
||||
content: WorldStateUpdateContent::Item(Box::new(tools.clone())),
|
||||
},
|
||||
WorldStateUpdate::fragment(fragment("developer", "after")),
|
||||
WorldStateUpdate::fragment(fragment("developer", "standalone")).standalone(),
|
||||
WorldStateUpdate::fragment(fragment("developer", "last developer")),
|
||||
WorldStateUpdate::fragment(fragment("user", "user")),
|
||||
WorldStateUpdate {
|
||||
placement: Placement::Standalone,
|
||||
content: WorldStateUpdateContent::Item(Box::new(tools.clone())),
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
merge_world_state_updates(updates),
|
||||
vec![
|
||||
message("developer", &["before one", "before two"]),
|
||||
message("developer", &["prefix"]),
|
||||
message("developer", &["after prefix"]),
|
||||
tools.clone(),
|
||||
message("developer", &["after"]),
|
||||
message("developer", &["standalone"]),
|
||||
message("developer", &["last developer"]),
|
||||
message("user", &["user"]),
|
||||
tools,
|
||||
]
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user