Repository navigation
feat(multimodal): [ATTACHMENT:] marker codec beside [IMAGE:]/[FILE:] #619
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| //! The marker vocabulary, and the pure string transforms over it. | ||
| //! | ||
| //! Four tokens make up the wire format between a host's ingress and its | ||
| //! Five tokens make up the wire format between a host's ingress and its | ||
| //! provider dispatch: | ||
| //! | ||
| //! | Token | Written by | Read by | | ||
|
|
@@ -9,22 +9,31 @@ | |
| //! | `[FILE:<ref>]` | the user / renderer | ingress, then dispatch | | ||
| //! | `[Image: <name> #att:<id>]` | ingress, replacing an image marker | dispatch, rehydrating | | ||
| //! | `[FILE-EXTRACTED:…]` / `[FILE-ATTACHED:…]` | [`payload`](super::payload) | the model | | ||
| //! | `[ATTACHMENT:<form-urlencoded JSON>]` | ingress, after persisting an upload | transcript and dispatch | | ||
| //! | ||
| //! The placeholder is mixed-case on purpose: `[Image:` never collides with the | ||
| //! `[IMAGE:` parser, so a persisted placeholder cannot be mistaken for an | ||
| //! unresolved attachment and re-read. | ||
| //! | ||
| //! Everything here is a pure function over `&str`. Message-level helpers — "how | ||
| //! many markers are in the latest user turn" — belong to the host, because only | ||
| //! the host knows what its message type is. | ||
| //! An `[ATTACHMENT:…]` reference ([`AttachmentRef`]) is the durable form of an | ||
| //! upload: compact metadata naming a workspace-relative path, never the bytes. | ||
| //! The codec here only encodes, decodes and rejects unsafe paths; where uploads | ||
| //! live and whether a path may be read stay host decisions. | ||
| //! | ||
| //! Everything here is a pure function over `&str` or over a single | ||
| //! [`Message`]. Transcript-level helpers — "how many markers are in the latest | ||
| //! user turn" — belong to the host, because only the host knows how its history | ||
| //! is shaped. | ||
|
|
||
| use std::collections::HashMap; | ||
| use std::path::PathBuf; | ||
| use std::path::{Component, Path, PathBuf}; | ||
|
|
||
| use base64::{ | ||
| Engine as _, | ||
| engine::general_purpose::{STANDARD, STANDARD_NO_PAD}, | ||
| }; | ||
| use serde::{Deserialize, Serialize}; | ||
| use tinyinference_llm::message::{ContentBlock, Message}; | ||
|
|
||
| /// Prefix of an inline image marker. | ||
| pub const IMAGE_MARKER_PREFIX: &str = "[IMAGE:"; | ||
|
|
@@ -255,3 +264,241 @@ pub fn rehydrate_placeholders_in_text(text: &str, index: &HashMap<String, PathBu | |
| out.push_str(&text[cursor..]); | ||
| out | ||
| } | ||
|
|
||
| /// Prefix of a compact attachment reference. The body is the | ||
| /// `application/x-www-form-urlencoded` serialization of an [`AttachmentRef`]'s | ||
| /// JSON, so it never contains a `]` and survives every text hop verbatim. | ||
| pub const ATTACHMENT_MARKER_PREFIX: &str = "[ATTACHMENT:"; | ||
|
|
||
| /// Fallback upload name when the original is empty or sanitizes to nothing. | ||
| const DEFAULT_ATTACHMENT_NAME: &str = "attachment"; | ||
|
|
||
| /// Longest sanitized upload filename, in UTF-8 bytes. | ||
| const MAX_ATTACHMENT_FILENAME_BYTES: usize = 180; | ||
|
|
||
| /// Metadata carried by an `[ATTACHMENT:…]` reference. | ||
| /// | ||
| /// `path` is relative to the host's acting workspace; [`attachment_segments`] | ||
| /// only yields references whose path passes [`is_safe_relative_path`]. Field | ||
| /// order is part of the wire format: it fixes the JSON the marker encodes. | ||
| #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] | ||
| pub struct AttachmentRef { | ||
| /// Workspace-relative path of the persisted original. | ||
| pub path: String, | ||
| /// Original, unsanitized display name. | ||
| pub name: String, | ||
| /// MIME type the host recorded for the original. | ||
| pub mime: String, | ||
| /// Size of the original in bytes. | ||
| pub size_bytes: usize, | ||
| } | ||
|
|
||
| impl AttachmentRef { | ||
| /// Render the `[ATTACHMENT:…]` marker for this reference. | ||
| pub fn marker(&self) -> String { | ||
| let json = serde_json::to_string(self).expect("attachment metadata serializes"); | ||
| format!( | ||
| "{ATTACHMENT_MARKER_PREFIX}{}]", | ||
| form_urlencoded::byte_serialize(json.as_bytes()).collect::<String>() | ||
| ) | ||
| } | ||
|
|
||
| /// The human-readable text a model sees in place of the marker. | ||
| pub fn description(&self) -> String { | ||
| format!( | ||
| "[Uploaded file: {}; {}; {} bytes; workspace path: {}]", | ||
| self.name, self.mime, self.size_bytes, self.path | ||
| ) | ||
| } | ||
|
|
||
| /// The reference `text` is the [`description`](Self::description) of, | ||
| /// when it is exactly one. The name may hold anything, so the fixed | ||
| /// fields are read from the right and the result must describe itself | ||
| /// back byte for byte. | ||
| pub fn from_description(text: &str) -> Option<Self> { | ||
| let body = text.strip_prefix("[Uploaded file: ")?.strip_suffix(']')?; | ||
| let (head, path) = body.rsplit_once("; workspace path: ")?; | ||
| let (head, size) = head.strip_suffix(" bytes")?.rsplit_once("; ")?; | ||
| let (name, mime) = head.rsplit_once("; ")?; | ||
| let attachment = Self { | ||
| path: path.into(), | ||
| name: name.into(), | ||
| mime: mime.into(), | ||
| size_bytes: size.parse().ok()?, | ||
| }; | ||
| (attachment.description() == text).then_some(attachment) | ||
| } | ||
| } | ||
|
|
||
| /// One piece of text split by [`attachment_segments`]. | ||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub enum AttachmentSegment { | ||
| /// Text between references, copied verbatim — including any marker that | ||
| /// failed to decode or named an unsafe path. | ||
| Text(String), | ||
| /// A well-formed reference with a safe relative path. | ||
| Attachment(AttachmentRef), | ||
| } | ||
|
|
||
| /// Split `text` into captions and `[ATTACHMENT:…]` references in source order. | ||
| /// | ||
| /// Nothing is trimmed. A marker that does not decode to an [`AttachmentRef`], | ||
| /// or whose path fails [`is_safe_relative_path`], stays in the text verbatim; | ||
| /// an unterminated marker ends the scan and is kept with the remainder. | ||
| pub fn attachment_segments(text: &str) -> Vec<AttachmentSegment> { | ||
| let mut rest = text; | ||
| let mut parts = Vec::new(); | ||
| while let Some(start) = rest.find(ATTACHMENT_MARKER_PREFIX) { | ||
| if start > 0 { | ||
| parts.push(AttachmentSegment::Text(rest[..start].into())); | ||
| } | ||
| let tail = &rest[start + ATTACHMENT_MARKER_PREFIX.len()..]; | ||
| let Some(end) = tail.find(']') else { | ||
| parts.push(AttachmentSegment::Text(rest[start..].into())); | ||
| return parts; | ||
| }; | ||
| let encoded = format!("value={}", &tail[..end]); | ||
| let decoded = form_urlencoded::parse(encoded.as_bytes()) | ||
| .next() | ||
| .map(|(_, value)| value.into_owned()); | ||
| match decoded.and_then(|json| serde_json::from_str::<AttachmentRef>(&json).ok()) { | ||
| Some(file) if is_safe_relative_path(&file.path) => { | ||
| parts.push(AttachmentSegment::Attachment(file)) | ||
| } | ||
| _ => parts.push(AttachmentSegment::Text( | ||
| rest[start..start + ATTACHMENT_MARKER_PREFIX.len() + end + 1].into(), | ||
| )), | ||
| } | ||
| rest = &tail[end + 1..]; | ||
| } | ||
| if !rest.is_empty() { | ||
| parts.push(AttachmentSegment::Text(rest.into())); | ||
| } | ||
| parts | ||
| } | ||
|
|
||
| /// Strip every valid `[ATTACHMENT:…]` reference and return | ||
| /// `(remaining_text, refs_in_order)`. | ||
| /// | ||
| /// Unlike [`parse_image_markers`], the remaining text is **not** trimmed: it is | ||
| /// the concatenation of every [`AttachmentSegment::Text`], byte for byte, so | ||
| /// ordinary prose is never reinterpreted as a path. | ||
| pub fn parse_attachment_markers(text: &str) -> (String, Vec<AttachmentRef>) { | ||
| let mut clean = String::new(); | ||
| let mut files = Vec::new(); | ||
| for segment in attachment_segments(text) { | ||
| match segment { | ||
| AttachmentSegment::Text(text) => clean.push_str(&text), | ||
| AttachmentSegment::Attachment(file) => files.push(file), | ||
| } | ||
| } | ||
| (clean, files) | ||
| } | ||
|
|
||
| /// `true` when `path` is a non-empty relative path made only of normal | ||
| /// components. | ||
| /// | ||
| /// Rejects NUL and every `\` (so Windows separators, drive paths such as | ||
| /// `C:\x` and UNC paths cannot slip through on Unix), a root or prefix, and | ||
| /// any `.` or `..` component. Judged per [`Path::components`] on the running | ||
| /// platform, which elides empty and interior `.` components (`a//b`, `a/./b` | ||
| /// are accepted as `a/b`). On Unix a forward-slash drive path such as `C:/x` | ||
| /// is an ordinary relative directory named `C:`; on Windows it is a prefix and | ||
| /// rejected. This is a shape check only: the host still authorizes the joined | ||
| /// path against its own policy. | ||
| pub fn is_safe_relative_path(path: &str) -> bool { | ||
| !path.is_empty() | ||
| && !path.contains(['\0', '\\']) | ||
| && Path::new(path) | ||
| .components() | ||
| .all(|c| matches!(c, Component::Normal(_))) | ||
| } | ||
|
|
||
| /// A filesystem-safe leaf name for a persisted upload. | ||
| /// | ||
| /// Keeps the last `/`- or `\`-separated component, replaces every character | ||
| /// other than alphanumerics, `.`, `-` and `_` with `_`, caps the result at 180 | ||
| /// UTF-8 bytes on a character boundary, and falls back to `attachment` when | ||
| /// nothing usable (or only `.` / `..`) remains. | ||
| pub fn sanitize_attachment_filename(name: &str) -> String { | ||
| let leaf = name | ||
| .rsplit(['/', '\\']) | ||
| .next() | ||
| .unwrap_or(DEFAULT_ATTACHMENT_NAME); | ||
| let mut sanitized = String::new(); | ||
| for c in leaf.chars() { | ||
| let c = if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') { | ||
| c | ||
| } else { | ||
| '_' | ||
| }; | ||
| if sanitized.len() + c.len_utf8() > MAX_ATTACHMENT_FILENAME_BYTES { | ||
| break; | ||
| } | ||
| sanitized.push(c); | ||
| } | ||
| if sanitized.is_empty() || sanitized == "." || sanitized == ".." { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject Windows device names in The function returns names such as Suggested fix
|
||
| DEFAULT_ATTACHMENT_NAME.into() | ||
| } else { | ||
| sanitized | ||
| } | ||
| } | ||
|
|
||
| /// Prefix the context a host added in front of a user turn's text without | ||
| /// flattening its typed media. | ||
| /// | ||
| /// `enriched` is `original_text` with context prepended; only that prefix is | ||
| /// inserted (all of `enriched` when it does not end with `original_text`). It | ||
| /// joins a leading text block so a plain turn keeps one text block, and | ||
| /// otherwise becomes a new first block. Non-user messages pass through. | ||
| pub fn enrich_user_message(input: Message, original_text: &str, enriched: &str) -> Message { | ||
| let Message::User(mut user) = input else { | ||
| return input; | ||
| }; | ||
| let prefix = enriched.strip_suffix(original_text).unwrap_or(enriched); | ||
| if !prefix.is_empty() { | ||
| if let Some(ContentBlock::Text(text)) = user.content.first_mut() { | ||
| text.insert_str(0, prefix); | ||
| } else { | ||
| user.content.insert(0, ContentBlock::Text(prefix.into())); | ||
| } | ||
| } | ||
| Message::User(user) | ||
| } | ||
|
|
||
| /// `legacy` followed by an `[IMAGE:<url>]` marker for each typed image block in | ||
| /// a user `input`, skipping duplicates — the image carrier a host forwards to a | ||
| /// delegated sub-agent without flattening the input. | ||
| pub fn image_markers_from_message(input: &Message, legacy: &[String]) -> Vec<String> { | ||
| let mut images = legacy.to_vec(); | ||
| if let Message::User(user) = input { | ||
| for block in &user.content { | ||
| if let ContentBlock::Image(image) = block { | ||
| let marker = format!("{IMAGE_MARKER_PREFIX}{}]", image.url); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve closing brackets in typed image references. A typed reference such as This changes the reference during forwarding. Use a lossless carrier, or add compatible escaping and decoding on both sides. Add a producer-to-parser round-trip test for bracket-bearing references.
|
||
| if !images.contains(&marker) { | ||
| images.push(marker); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| images | ||
| } | ||
|
|
||
| /// `true` when a delegation `prompt` selects no image itself, so the parent's | ||
| /// images should be forwarded automatically. | ||
| /// | ||
| /// An image `[ATTACHMENT:…]` reference, an `[IMAGE:…]` marker or an | ||
| /// `[Image: … #att:<id>]` placeholder is an explicit selection and replaces | ||
| /// automatic forwarding. | ||
| pub fn should_forward_parent_images(prompt: &str) -> bool { | ||
| parse_attachment_markers(prompt) | ||
| .1 | ||
| .iter() | ||
| .all(|file| !file.mime.starts_with("image/")) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Compare the image MIME type without case sensitivity. MIME type names are case-insensitive. (rfc-editor.org) With a valid attachment whose The helper then requests parent-image forwarding despite an explicit image selection. Compare the top-level MIME type with
|
||
| && parse_image_markers(prompt).1.is_empty() | ||
| && extract_image_placeholders_in_text(prompt).is_empty() | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "markers_tests.rs"] | ||
| mod tests; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve metadata when parsing descriptions.
With
name="report"andmime="text/plain; charset=utf-8", this split returnsname="report; text/plain"andmime="charset=utf-8". MIME parameters are valid. (rfc-editor.org)Line 329 accepts the changed metadata because it renders to the same text. The canonical-text check does not prove a round trip. Make the field representation unambiguous, or enforce an explicit field restriction before rendering. Add a round-trip case with MIME parameters.