The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: remove unused document format module
Steven Enamakelce4c1a42cafc
diff --git a/src/openhuman/tools/impl/document/format/error/mod.rs b/src/openhuman/tools/impl/document/format/error/mod.rsdeleted file mode 100644index e46245b59d..0000000000--- a/src/openhuman/tools/impl/document/format/error/mod.rs+++ /dev/null@@ -1,120 +0,0 @@-//! Crate-wide error and result types.-//!-//! Every fallible public function in this crate returns [`Result`], and every-//! failure mode is a distinct [`Error`] variant. Add a variant rather than-//! encoding new context into an existing message: callers match on variants,-//! and message text is not a stable API.-//!-//! The variants are deliberately *host-agnostic*. A host that surfaces these-//! to an LLM (the reason [`Error::InvalidInput`] carries a structured-//! `field` / `reason` pair rather than a formatted sentence) maps them onto-//! its own tool-error shape; a host writing to disk maps them onto its own.-//! Nothing here knows about artifacts, timeouts, or async runtimes — those are-//! the host's concerns, because only the host knows its own deadline policy.--/// Errors returned by this crate.-#[derive(Debug, thiserror::Error, PartialEq, Eq)]-#[non_exhaustive]-pub enum Error {- /// A document spec failed validation before any synthesis was attempted.- ///- /// `field` names the offending path in the spec using the same dotted /- /// indexed notation the JSON input uses (`sections[2].bullets[0]`), so an- /// LLM that produced the spec can self-correct without re-reading the- /// whole schema. `reason` states the violated constraint.- #[error("invalid input for field '{field}': {reason}")]- InvalidInput {- /// Path of the offending field within the spec.- field: String,- /// The constraint that was violated.- reason: String,- },-- /// The underlying document library failed to synthesise the output.- ///- /// `detail` is the library's own error rendered as text and truncated to a- /// bounded length, so the variant never carries an unbounded payload back- /// to a caller that forwards it to a model.- #[error("document generation failed: {detail}")]- GenerationFailed {- /// Truncated underlying library error.- detail: String,- },-- /// The underlying library failed to extract text from an input document.- ///- /// Distinct from [`Error::GenerationFailed`] because the two have opposite- /// causes and opposite remedies: generation fails on *our* output path and- /// usually means a bug or an exhausted resource, whereas extraction fails on- /// *someone else's* input and usually means the document is damaged,- /// encrypted, or carries no extractable text layer at all. A caller that- /// retries one should not retry the other.- ///- /// `detail` is truncated on the same bound as `GenerationFailed`.- #[error("text extraction failed: {detail}")]- ExtractionFailed {- /// Truncated underlying library error.- detail: String,- },-}--impl Error {- /// Maximum length, in Unicode scalar values, of a [`Error::GenerationFailed`]- /// detail string.- pub const MAX_DETAIL_CHARS: usize = 500;-- /// Suffix appended when a detail string is truncated.- const TRUNCATION_SUFFIX: &'static str = " […truncated]";-- /// Build a [`Error::GenerationFailed`] with `raw` truncated (UTF-8-safe) to- /// [`Error::MAX_DETAIL_CHARS`].- ///- /// Truncation counts characters, not bytes, so a multi-byte error message- /// can never be cut mid-codepoint.- #[must_use]- pub fn generation_failed(raw: &str) -> Self {- Self::GenerationFailed {- detail: Self::truncate_detail(raw),- }- }-- /// Truncate `raw` to [`Error::MAX_DETAIL_CHARS`] characters, appending the- /// standard truncation suffix when anything was dropped.- #[must_use]- pub fn truncate_detail(raw: &str) -> String {- if raw.chars().count() <= Self::MAX_DETAIL_CHARS {- return raw.to_string();- }- let keep = Self::MAX_DETAIL_CHARS.saturating_sub(Self::TRUNCATION_SUFFIX.chars().count());- let mut out: String = raw.chars().take(keep).collect();- out.push_str(Self::TRUNCATION_SUFFIX);- out- }-- /// Build an [`Error::ExtractionFailed`] with `raw` truncated (UTF-8-safe) to- /// [`Error::MAX_DETAIL_CHARS`].- #[must_use]- pub fn extraction_failed(raw: &str) -> Self {- Self::ExtractionFailed {- detail: Self::truncate_detail(raw),- }- }-- /// Build an [`Error::InvalidInput`] for `field` violating `reason`.- #[must_use]- pub fn invalid_input(field: impl Into<String>, reason: impl Into<String>) -> Self {- Self::InvalidInput {- field: field.into(),- reason: reason.into(),- }- }-}--/// The crate's standard result type.-///-/// Use this alias in public signatures instead of spelling out-/// `std::result::Result<T, Error>`.-pub type Result<T> = std::result::Result<T, Error>;--#[cfg(test)]-mod test;diff --git a/src/openhuman/tools/impl/document/format/error/test.rs b/src/openhuman/tools/impl/document/format/error/test.rsdeleted file mode 100644index 7bc5815fc1..0000000000--- a/src/openhuman/tools/impl/document/format/error/test.rs+++ /dev/null@@ -1,54 +0,0 @@-//! Unit tests for the crate-wide error type.--#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]--use super::Error;--#[test]-fn short_details_are_left_intact() {- let err = Error::generation_failed("boom");- assert_eq!(- err,- Error::GenerationFailed {- detail: "boom".to_string()- }- );-}--#[test]-fn long_details_are_truncated_with_a_suffix() {- let raw = "x".repeat(Error::MAX_DETAIL_CHARS * 2);- let Error::GenerationFailed { detail } = Error::generation_failed(&raw) else {- panic!("expected GenerationFailed");- };- assert_eq!(detail.chars().count(), Error::MAX_DETAIL_CHARS);- assert!(detail.ends_with("[…truncated]"));-}--#[test]-fn truncation_never_splits_a_multi_byte_character() {- // Every character is 4 bytes, so a byte-based truncation would panic or- // produce invalid UTF-8. Counting characters keeps the boundary valid.- let raw = "🦀".repeat(Error::MAX_DETAIL_CHARS * 2);- let detail = Error::truncate_detail(&raw);- assert_eq!(detail.chars().count(), Error::MAX_DETAIL_CHARS);- assert!(detail.starts_with('🦀'));-}--#[test]-fn detail_at_exactly_the_cap_is_not_truncated() {- let raw = "y".repeat(Error::MAX_DETAIL_CHARS);- assert_eq!(Error::truncate_detail(&raw), raw);-}--#[test]-fn invalid_input_carries_the_field_path_verbatim() {- let err = Error::invalid_input("sections[2].bullets[0]", "must be ≤ 10 chars");- assert_eq!(- err,- Error::InvalidInput {- field: "sections[2].bullets[0]".to_string(),- reason: "must be ≤ 10 chars".to_string(),- }- );-}diff --git a/src/openhuman/tools/impl/document/format/mod.rs b/src/openhuman/tools/impl/document/format/mod.rsdeleted file mode 100644index 81c45df4d8..0000000000--- a/src/openhuman/tools/impl/document/format/mod.rs+++ /dev/null@@ -1,29 +0,0 @@-//! Agent-friendly document synthesis and text extraction in Rust.-//!-//! Typed, validated document contracts shared with the document bus module.-//! They are built for hosts that let a language model produce documents:-//! the spec types are the JSON tool schema, validation rejects a malformed-//! spec with a structured [`Error::InvalidInput`] naming the exact field so-//! the model can self-correct, and synthesis returns a plain byte buffer.-//!-//! # What this module deliberately does not do-//!-//! No filesystem access, no subprocesses, no async runtime, no deadline-//! handling. Synthesis runs in the document bus module; this host module owns-//! the wire contract and validation only.-//!-//! # Layout-//!-//! - [`error`](self::Error) — the crate-wide [`Error`] and [`Result`].-//! - [`spec`] — the typed document specs and their validation. Compiled in-//! every build, including `--no-default-features`, so a host whose synthesis-//! happens elsewhere still shares one definition of the wire contract.-//!-//! Writer and extractor implementations are intentionally absent: the host-//! sends these contract values over TinyBus.--mod error;--pub mod spec;--pub use error::{Error, Result};diff --git a/src/openhuman/tools/impl/document/format/spec/document/mod.rs b/src/openhuman/tools/impl/document/format/spec/document/mod.rsdeleted file mode 100644index d96e78f429..0000000000--- a/src/openhuman/tools/impl/document/format/spec/document/mod.rs+++ /dev/null@@ -1,261 +0,0 @@-//! The `.docx` document spec: the typed description a caller hands to-//! `docx::generate`, plus the size limits every spec is validated against.-//!-//! The spec is the crate's wire contract. It derives `Serialize` /-//! `Deserialize` with `deny_unknown_fields` because the usual caller is an-//! LLM tool boundary: the same struct that drives synthesis is the one whose-//! JSON schema the model is shown, and a typo'd field name should be a loud-//! rejection rather than a silently ignored key.-//!-//! Limits are public consts rather than private constants so a host can quote-//! the exact number in its own tool description and stay in lockstep with what-//! validation actually enforces.-//!-//! Nothing in this module depends on the `docx` feature or on `docx-rs`: it is-//! `serde` plus the crate error type. A host that only needs to *describe* and-//! *validate* a document — because synthesis happens elsewhere, in another-//! process or behind a message bus — can therefore depend on this crate with-//! `default-features = false` and still share one definition of the contract.--use serde::{Deserialize, Serialize};--use crate::openhuman::tools::implementations::document::format::{Error, Result};--/// Maximum number of sections a single document may contain.-///-/// Bounds generation time and output size; a caller with more material is-/// expected to split it across multiple documents.-pub const MAX_SECTIONS: usize = 128;--/// Maximum length, in Unicode scalar values, of a short text field — the-/// document title, the author byline, or a section heading.-pub const MAX_TEXT_CHARS: usize = 2_000;--/// Maximum length, in Unicode scalar values, of a single body paragraph or-/// bullet item.-///-/// More generous than [`MAX_TEXT_CHARS`]: prose paragraphs legitimately run-/// far longer than a heading.-pub const MAX_PARAGRAPH_CHARS: usize = 20_000;--/// Maximum number of body paragraphs in a single section.-pub const MAX_PARAGRAPHS_PER_SECTION: usize = 200;--/// Maximum number of bullet-list items in a single section.-pub const MAX_BULLETS_PER_SECTION: usize = 200;--/// Aggregate cap on all renderable text across the whole document — the-/// title, the author byline, and every section's heading, paragraphs, and-/// bullets — in Unicode scalar values.-///-/// The per-field and per-section limits above bound each individual piece, but-/// not their product — `MAX_SECTIONS × MAX_PARAGRAPHS_PER_SECTION ×-/// MAX_PARAGRAPH_CHARS` alone is over 500M characters, so a spec satisfying-/// every other limit could still build a multi-hundred-megabyte document in-/// memory. This total keeps the worst case bounded to a few megabytes of text-/// while staying generous for any real document.-pub const MAX_TOTAL_CHARS: usize = 2_000_000;--/// One section of the document, rendered in spec order.-///-/// A section is an optional heading followed by any number of body paragraphs-/// and/or a bullet list. At least one of the three must carry renderable text —-/// a wholly blank section is rejected by [`DocumentSpec::validate`] rather than-/// silently rendering nothing.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct DocumentSection {- /// Section heading, rendered as a bold heading paragraph. Optional: a- /// section may be pure body text under the document title.- #[serde(default)]- pub heading: Option<String>,- /// Body paragraphs, each rendered as its own paragraph, in order.- /// Blank and whitespace-only entries are dropped during synthesis.- #[serde(default)]- pub paragraphs: Vec<String>,- /// Bullet-list items, rendered as a single-level bulleted list after the- /// section's body paragraphs. Blank and whitespace-only entries are- /// dropped during synthesis.- #[serde(default)]- pub bullets: Vec<String>,-}--impl DocumentSection {- /// Returns `true` when the section carries no renderable content at all —- /// the heading is absent or blank, and every paragraph and bullet is blank.- ///- /// Synthesis trims and drops blank entries, so a section holding only- /// `[" "]` would render as nothing despite carrying entries. Validation- /// uses this to reject that case up front.- #[must_use]- pub fn is_blank(&self) -> bool {- let has_heading = self- .heading- .as_deref()- .is_some_and(|h| !h.trim().is_empty());- let has_paragraph = self.paragraphs.iter().any(|p| !p.trim().is_empty());- let has_bullet = self.bullets.iter().any(|b| !b.trim().is_empty());- !(has_heading || has_paragraph || has_bullet)- }-}--/// A complete `.docx` document spec.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct DocumentSpec {- /// Document title, rendered as the leading title paragraph. Required and- /// non-blank.- pub title: String,- /// Optional author byline, rendered as an italic line beneath the title.- #[serde(default)]- pub author: Option<String>,- /// Sections, in display order. Must contain at least one entry.- #[serde(default)]- pub sections: Vec<DocumentSection>,-}--impl DocumentSpec {- /// Total renderable text across the whole spec, in Unicode scalar values.- ///- /// Sums with saturating arithmetic so an adversarial spec cannot overflow- /// the counter into a small value that passes the aggregate check.- #[must_use]- pub fn total_chars(&self) -> usize {- let mut total = self.title.chars().count();- if let Some(author) = self.author.as_deref() {- total = total.saturating_add(author.chars().count());- }- for section in &self.sections {- if let Some(heading) = section.heading.as_deref() {- total = total.saturating_add(heading.chars().count());- }- for paragraph in §ion.paragraphs {- total = total.saturating_add(paragraph.chars().count());- }- for bullet in §ion.bullets {- total = total.saturating_add(bullet.chars().count());- }- }- total- }-- /// Check the spec against every documented size limit.- ///- /// Callers do not have to invoke this: `docx::generate` validates before it- /// synthesises anything. It is public so a host can reject a malformed- /// spec at its own boundary — an LLM tool call, say — and hand back the- /// structured [`Error::InvalidInput`] before paying for a blocking hop, a- /// process boundary, or a bus round trip.- ///- /// # Errors- ///- /// Returns [`Error::InvalidInput`] naming the first field that violates a- /// limit. Fields are checked in spec order (title, author, sections, then- /// each section's contents) so the reported field is stable for a given- /// spec.- pub fn validate(&self) -> Result<()> {- if self.title.trim().is_empty() {- return Err(Error::invalid_input("title", "must not be empty"));- }- if self.title.chars().count() > MAX_TEXT_CHARS {- return Err(Error::invalid_input(- "title",- format!("must be ≤ {MAX_TEXT_CHARS} chars"),- ));- }- // Running total across every renderable field — title, author, and all- // section contents — checked as each field is processed. A spec can pass- // every per-field limit yet blow the aggregate budget, and checking- // incrementally rejects it as soon as the budget is crossed without a- // second pass over the whole spec.- let over_budget = || {- Error::invalid_input(- "sections",- format!("total document text must be ≤ {MAX_TOTAL_CHARS} chars"),- )- };- let mut total = self.title.chars().count();- if let Some(author) = self.author.as_deref() {- if author.chars().count() > MAX_TEXT_CHARS {- return Err(Error::invalid_input(- "author",- format!("must be ≤ {MAX_TEXT_CHARS} chars"),- ));- }- total = total.saturating_add(author.chars().count());- }- if self.sections.is_empty() {- return Err(Error::invalid_input(- "sections",- "must contain at least one section",- ));- }- if self.sections.len() > MAX_SECTIONS {- return Err(Error::invalid_input(- "sections",- format!("must contain ≤ {MAX_SECTIONS} sections"),- ));- }-- for (i, section) in self.sections.iter().enumerate() {- if section.is_blank() {- return Err(Error::invalid_input(- format!("sections[{i}]"),- "must have at least one of heading / paragraphs / bullets",- ));- }- if let Some(heading) = section.heading.as_deref() {- if heading.chars().count() > MAX_TEXT_CHARS {- return Err(Error::invalid_input(- format!("sections[{i}].heading"),- format!("must be ≤ {MAX_TEXT_CHARS} chars"),- ));- }- total = total.saturating_add(heading.chars().count());- if total > MAX_TOTAL_CHARS {- return Err(over_budget());- }- }- if section.paragraphs.len() > MAX_PARAGRAPHS_PER_SECTION {- return Err(Error::invalid_input(- format!("sections[{i}].paragraphs"),- format!("must contain ≤ {MAX_PARAGRAPHS_PER_SECTION} paragraphs"),- ));- }- for (p, paragraph) in section.paragraphs.iter().enumerate() {- if paragraph.chars().count() > MAX_PARAGRAPH_CHARS {- return Err(Error::invalid_input(- format!("sections[{i}].paragraphs[{p}]"),- format!("must be ≤ {MAX_PARAGRAPH_CHARS} chars"),- ));- }- total = total.saturating_add(paragraph.chars().count());- if total > MAX_TOTAL_CHARS {- return Err(over_budget());- }- }- if section.bullets.len() > MAX_BULLETS_PER_SECTION {- return Err(Error::invalid_input(- format!("sections[{i}].bullets"),- format!("must contain ≤ {MAX_BULLETS_PER_SECTION} bullets"),- ));- }- for (b, bullet) in section.bullets.iter().enumerate() {- if bullet.chars().count() > MAX_PARAGRAPH_CHARS {- return Err(Error::invalid_input(- format!("sections[{i}].bullets[{b}]"),- format!("must be ≤ {MAX_PARAGRAPH_CHARS} chars"),- ));- }- total = total.saturating_add(bullet.chars().count());- if total > MAX_TOTAL_CHARS {- return Err(over_budget());- }- }- }- Ok(())- }-}--#[cfg(test)]-mod test;diff --git a/src/openhuman/tools/impl/document/format/spec/document/test.rs b/src/openhuman/tools/impl/document/format/spec/document/test.rsdeleted file mode 100644index 724302217e..0000000000--- a/src/openhuman/tools/impl/document/format/spec/document/test.rs+++ /dev/null@@ -1,272 +0,0 @@-//! Unit tests for the wire contracts: validation, the blank/aggregate rules,-//! and JSON round-tripping.-//!-//! These are deliberately separate from the format modules' tests. They must-//! pass in a build with every format feature off, because the spec is the half-//! of the crate a bus- or process-boundary host shares without the codec.--#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]--use super::{- DocumentSection, DocumentSpec, MAX_BULLETS_PER_SECTION, MAX_PARAGRAPHS_PER_SECTION,- MAX_PARAGRAPH_CHARS, MAX_SECTIONS, MAX_TEXT_CHARS, MAX_TOTAL_CHARS,-};-use crate::openhuman::tools::implementations::document::format::Error;--/// One valid section carrying a heading, a paragraph, and a bullet.-fn section() -> DocumentSection {- DocumentSection {- heading: Some("Overview".to_string()),- paragraphs: vec!["A body paragraph.".to_string()],- bullets: vec!["A bullet".to_string()],- }-}--/// A minimal valid spec; each test mutates one field to drive a single branch.-fn spec() -> DocumentSpec {- DocumentSpec {- title: "Charter".to_string(),- author: Some("Alice".to_string()),- sections: vec![section()],- }-}--/// Assert `spec` is rejected with an `InvalidInput` naming `field`.-fn assert_rejects(spec: &DocumentSpec, field: &str) {- match spec.validate() {- Err(Error::InvalidInput { field: f, .. }) => {- assert_eq!(f, field, "unexpected rejected field");- }- other => panic!("expected InvalidInput({field}), got {other:?}"),- }-}--#[test]-fn accepts_a_well_formed_spec() {- assert!(spec().validate().is_ok());-}--#[test]-fn rejects_a_blank_title() {- let mut s = spec();- s.title = " ".to_string();- assert_rejects(&s, "title");-}--#[test]-fn rejects_an_over_long_title() {- let mut s = spec();- s.title = "t".repeat(MAX_TEXT_CHARS + 1);- assert_rejects(&s, "title");-}--#[test]-fn rejects_an_over_long_author() {- let mut s = spec();- s.author = Some("a".repeat(MAX_TEXT_CHARS + 1));- assert_rejects(&s, "author");-}--#[test]-fn rejects_a_spec_with_no_sections() {- let mut s = spec();- s.sections.clear();- assert_rejects(&s, "sections");-}--#[test]-fn rejects_too_many_sections() {- let mut s = spec();- s.sections = vec![section(); MAX_SECTIONS + 1];- assert_rejects(&s, "sections");-}--#[test]-fn rejects_a_wholly_blank_section() {- // Every entry is present but whitespace-only, so synthesis would drop all- // of them and render nothing. Validation catches it instead.- let mut s = spec();- s.sections = vec![DocumentSection {- heading: Some(" ".to_string()),- paragraphs: vec!["\t".to_string()],- bullets: vec![String::new()],- }];- assert_rejects(&s, "sections[0]");-}--#[test]-fn rejects_an_over_long_heading_naming_its_index() {- let mut s = spec();- s.sections.push(DocumentSection {- heading: Some("h".repeat(MAX_TEXT_CHARS + 1)),- ..section()- });- assert_rejects(&s, "sections[1].heading");-}--#[test]-fn rejects_too_many_paragraphs() {- let mut s = spec();- s.sections[0].paragraphs = vec!["p".to_string(); MAX_PARAGRAPHS_PER_SECTION + 1];- assert_rejects(&s, "sections[0].paragraphs");-}--#[test]-fn rejects_an_over_long_paragraph_naming_its_index() {- let mut s = spec();- s.sections[0].paragraphs = vec!["ok".to_string(), "p".repeat(MAX_PARAGRAPH_CHARS + 1)];- assert_rejects(&s, "sections[0].paragraphs[1]");-}--#[test]-fn rejects_too_many_bullets() {- let mut s = spec();- s.sections[0].bullets = vec!["b".to_string(); MAX_BULLETS_PER_SECTION + 1];- assert_rejects(&s, "sections[0].bullets");-}--#[test]-fn rejects_an_over_long_bullet_naming_its_index() {- let mut s = spec();- s.sections[0].bullets = vec!["ok".to_string(), "b".repeat(MAX_PARAGRAPH_CHARS + 1)];- assert_rejects(&s, "sections[0].bullets[1]");-}--#[test]-fn rejects_a_spec_over_the_aggregate_character_budget() {- // Each individual field is within its own limit; only the sum is not. One- // section with just enough max-length paragraphs to cross MAX_TOTAL_CHARS- // reproduces that without allocating hundreds of megabytes: repeating a- // whole section MAX_SECTIONS times (the original fixture) built ~512 MB- // of paragraph text before validation ever ran.- let paragraph_count = MAX_TOTAL_CHARS / MAX_PARAGRAPH_CHARS + 1;- assert!(paragraph_count <= MAX_PARAGRAPHS_PER_SECTION);- let paragraph = "x".repeat(MAX_PARAGRAPH_CHARS);- let big = DocumentSection {- heading: Some("Heading".to_string()),- paragraphs: vec![paragraph; paragraph_count],- bullets: vec![],- };- let s = DocumentSpec {- title: "Huge".to_string(),- author: None,- sections: vec![big],- };- // Sanity: this spec passes every per-field check.- assert!(s.sections.len() <= MAX_SECTIONS);- assert_rejects(&s, "sections");-}--#[test]-fn rejects_an_aggregate_overrun_that_a_bullet_crosses() {- // The heading and paragraph loops each carry their own budget check; so does- // the bullet loop, and only a spec whose overrun lands on a bullet drives- // that third branch.- let bullet = "b".repeat(MAX_PARAGRAPH_CHARS);- let bullet_count = MAX_TOTAL_CHARS / MAX_PARAGRAPH_CHARS + 1;- assert!(bullet_count <= MAX_BULLETS_PER_SECTION);- let s = DocumentSpec {- title: "Bullets".to_string(),- author: None,- sections: vec![DocumentSection {- heading: None,- paragraphs: vec![],- bullets: vec![bullet; bullet_count],- }],- };- assert_rejects(&s, "sections");-}--#[test]-fn rejects_an_aggregate_overrun_that_a_heading_crosses() {- // Headings cannot reach the aggregate cap on their own: MAX_SECTIONS ×- // MAX_TEXT_CHARS is 256_000, two orders of magnitude under MAX_TOTAL_CHARS.- // Driving the heading branch therefore means spending the budget down to a- // single character of headroom in an earlier section, then letting a- // perfectly legal heading cross it.- let title = "Headings";- let filler_count = MAX_TOTAL_CHARS / MAX_PARAGRAPH_CHARS - 1;- assert!(filler_count <= MAX_PARAGRAPHS_PER_SECTION);- let used = title.chars().count() + filler_count * MAX_PARAGRAPH_CHARS;- // Leave exactly one character of headroom.- let tail = MAX_TOTAL_CHARS - used - 1;- assert!(tail <= MAX_PARAGRAPH_CHARS);-- let mut paragraphs = vec!["p".repeat(MAX_PARAGRAPH_CHARS); filler_count];- paragraphs.push("p".repeat(tail));-- let s = DocumentSpec {- title: title.to_string(),- author: None,- sections: vec![- DocumentSection {- heading: None,- paragraphs,- bullets: vec![],- },- DocumentSection {- // Two characters against one character of headroom.- heading: Some("hh".to_string()),- paragraphs: vec![],- bullets: vec![],- },- ],- };- assert!(s.sections.len() <= MAX_SECTIONS);- assert_rejects(&s, "sections");-}--#[test]-fn is_blank_reflects_content_presence() {- assert!(!section().is_blank());- assert!(DocumentSection {- heading: None,- paragraphs: vec![],- bullets: vec![],- }- .is_blank());- // A heading alone is enough content.- assert!(!DocumentSection {- heading: Some("Only a heading".to_string()),- paragraphs: vec![],- bullets: vec![],- }- .is_blank());-}--#[test]-fn total_chars_sums_every_text_field() {- let s = DocumentSpec {- title: "abcd".to_string(), // 4- author: Some("xy".to_string()), // 2- sections: vec![DocumentSection {- heading: Some("hij".to_string()), // 3- paragraphs: vec!["pq".to_string()], // 2- bullets: vec!["b".to_string()], // 1- }],- };- assert_eq!(s.total_chars(), 12);-}--#[test]-fn spec_round_trips_through_json() {- let s = spec();- let json = serde_json::to_string(&s).expect("serialises");- let back: DocumentSpec = serde_json::from_str(&json).expect("deserialises");- assert_eq!(back, s);-}--#[test]-fn spec_rejects_unknown_json_fields() {- // `deny_unknown_fields` makes a typo'd key a loud rejection rather than a- // silently ignored one — the whole point at an LLM tool boundary.- let json = r#"{"title":"T","sections":[],"titel":"typo"}"#;- assert!(serde_json::from_str::<DocumentSpec>(json).is_err());-}--#[test]-fn spec_defaults_optional_fields() {- let s: DocumentSpec = serde_json::from_str(r#"{"title":"T"}"#).expect("deserialises");- assert_eq!(s.author, None);- assert!(s.sections.is_empty());-}diff --git a/src/openhuman/tools/impl/document/format/spec/image/mod.rs b/src/openhuman/tools/impl/document/format/spec/image/mod.rsdeleted file mode 100644index 4fab9d934e..0000000000--- a/src/openhuman/tools/impl/document/format/spec/image/mod.rs+++ /dev/null@@ -1,161 +0,0 @@-//! Raster-image identification for specs that embed images.-//!-//! Two formats are supported, PNG and JPEG, and the restriction is deliberate-//! rather than incidental: the OOXML presentation writer this crate drives-//! declares no `webp` default in the generated `[Content_Types].xml`, and its-//! automatic format detection misclassifies `webp` as PNG — producing a part-//! `PowerPoint` refuses to render. Accepting only what can actually be embedded-//! turns that into a clean rejection at the boundary.-//!-//! Identification is done by reading the container header directly, in about a-//! hundred lines and with no dependencies, rather than by pulling in a decoding-//! stack. Nothing here decodes pixels: it answers "which format is this" and-//! "what are its native dimensions", which is all a layout engine needs to-//! place an image with the right aspect ratio.-//!-//! Like the rest of [`crate::openhuman::tools::implementations::document::format::spec`], this module is compiled in every build. A-//! host resolving image bytes has to identify and measure them to *build* a-//! spec, and that must not require the writer.--use serde::{Deserialize, Serialize};--/// A raster image format that can be embedded in a generated document.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "UPPERCASE")]-pub enum ImageFormat {- /// Portable Network Graphics.- Png,- /// JPEG / JFIF.- Jpeg,-}--impl ImageFormat {- /// The format's canonical OOXML name — `"PNG"` or `"JPEG"`.- #[must_use]- pub const fn as_str(self) -> &'static str {- match self {- Self::Png => "PNG",- Self::Jpeg => "JPEG",- }- }-- /// Identify `bytes` by its container header.- ///- /// Returns `None` for a truncated header or any format other than the two- /// embeddable ones — including GIF, WebP and BMP, which are recognisable- /// but not embeddable.- #[must_use]- pub fn sniff(bytes: &[u8]) -> Option<Self> {- if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {- Some(Self::Png)- } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {- Some(Self::Jpeg)- } else {- None- }- }-- /// Native `(width, height)` of `bytes` in pixels, read from the header.- ///- /// Returns `None` when the header is truncated or malformed, or when either- /// dimension is zero — a degenerate image cannot be placed aspect-correctly- /// and is rejected rather than divided by.- #[must_use]- pub fn dimensions(self, bytes: &[u8]) -> Option<(u32, u32)> {- match self {- Self::Png => png_dimensions(bytes),- Self::Jpeg => jpeg_dimensions(bytes),- }- }-}--impl std::fmt::Display for ImageFormat {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(self.as_str())- }-}--/// PNG: 8-byte signature, then an `IHDR` chunk whose width / height are-/// big-endian `u32`s at byte offsets 16 and 20.-fn png_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {- if bytes.len() < 24 || &bytes[12..16] != b"IHDR" {- return None;- }- let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);- let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);- if w == 0 || h == 0 {- return None;- }- Some((w, h))-}--/// JPEG: walk the marker segments until a Start-Of-Frame is hit; its payload-/// carries height then width as big-endian `u16`s.-fn jpeg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {- let mut i = 2; // skip the leading FF D8 SOI- while i + 3 < bytes.len() {- if bytes[i] != 0xFF {- i += 1;- continue;- }- let marker = bytes[i + 1];- i += 2;- // Standalone markers carry no length field: padding fill bytes, TEM,- // RSTn, SOI and EOI. Reading the next two bytes as a length here would- // desynchronise the walk and reject a valid file — TEM in particular is- // legal before the frame header.- if marker == 0xFF- || marker == 0x01- || marker == 0xD8- || marker == 0xD9- || (0xD0..=0xD7).contains(&marker)- {- continue;- }- if i + 1 >= bytes.len() {- return None;- }- let seg_len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize;- if seg_len < 2 {- return None;- }- // SOF markers carrying frame dimensions. Excludes 0xC4 (DHT),- // 0xC8 (JPG) and 0xCC (DAC), which share the 0xCn range but are not- // frame headers.- let is_sof = matches!(- marker,- 0xC0 | 0xC1- | 0xC2- | 0xC3- | 0xC5- | 0xC6- | 0xC7- | 0xC9- | 0xCA- | 0xCB- | 0xCD- | 0xCE- | 0xCF- );- if is_sof {- // segment: [len_hi len_lo precision h_hi h_lo w_hi w_lo ...]- if i + 6 >= bytes.len() {- return None;- }- let h = u32::from(u16::from_be_bytes([bytes[i + 3], bytes[i + 4]]));- let w = u32::from(u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]));- if w == 0 || h == 0 {- return None;- }- return Some((w, h));- }- i += seg_len;- }- None-}--// Visible crate-wide under `cfg(test)`: the `png` / `jpeg` header builders here-// are the fixtures every image-carrying spec and every synthesis test needs, and-// one honest builder beats a base64 blob copied into three files.-#[cfg(test)]-pub(crate) mod test;diff --git a/src/openhuman/tools/impl/document/format/spec/image/test.rs b/src/openhuman/tools/impl/document/format/spec/image/test.rsdeleted file mode 100644index 90206fce8a..0000000000--- a/src/openhuman/tools/impl/document/format/spec/image/test.rs+++ /dev/null@@ -1,151 +0,0 @@-//! Unit tests for image identification and header measurement.--#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]--use super::{jpeg_dimensions, png_dimensions, ImageFormat};--/// A 1×1 PNG assembled byte-for-byte: signature, `IHDR`, `IDAT`, `IEND`.-///-/// Built literally rather than decoded from base64 so the fixture needs no-/// dependency and the offsets under test are visible in the source.-pub(crate) fn png(width: u32, height: u32) -> Vec<u8> {- let mut out = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];- out.extend_from_slice(&13u32.to_be_bytes()); // IHDR length- out.extend_from_slice(b"IHDR");- out.extend_from_slice(&width.to_be_bytes());- out.extend_from_slice(&height.to_be_bytes());- out.extend_from_slice(&[0x08, 0x06, 0x00, 0x00, 0x00]); // depth, colour, etc.- out.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // CRC placeholder- out.extend_from_slice(&0u32.to_be_bytes()); // empty IDAT- out.extend_from_slice(b"IDAT");- out.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);- out.extend_from_slice(&0u32.to_be_bytes());- out.extend_from_slice(b"IEND");- out.extend_from_slice(&[0xAE, 0x42, 0x60, 0x82]);- out-}--/// A minimal JPEG: SOI, an APP0 stub, then an SOF0 declaring `height × width`.-pub(crate) fn jpeg(width: u16, height: u16) -> Vec<u8> {- let mut out = vec![- 0xFF, 0xD8, // SOI- 0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00, // APP0, len=4, 2 payload bytes- 0xFF, 0xC0, 0x00, 0x0B, // SOF0, len=11- 0x08, // precision- ];- out.extend_from_slice(&height.to_be_bytes());- out.extend_from_slice(&width.to_be_bytes());- out.extend_from_slice(&[0x03, 0x00, 0x00, 0x00]); // components (filler)- out.extend_from_slice(&[0xFF, 0xD9]); // EOI- out-}--#[test]-fn sniffs_png_and_jpeg() {- assert_eq!(ImageFormat::sniff(&png(1, 1)), Some(ImageFormat::Png));- assert_eq!(ImageFormat::sniff(&jpeg(7, 5)), Some(ImageFormat::Jpeg));-}--#[test]-fn rejects_non_images_and_unembeddable_formats() {- assert_eq!(ImageFormat::sniff(b"not an image"), None);- // GIF and WebP are recognisable, but the writer cannot embed either.- assert_eq!(ImageFormat::sniff(b"GIF89a....."), None);- assert_eq!(ImageFormat::sniff(b"RIFF\0\0\0\0WEBP"), None);- assert_eq!(ImageFormat::sniff(&[]), None);-}--#[test]-fn reads_png_dimensions() {- assert_eq!(ImageFormat::Png.dimensions(&png(1, 1)), Some((1, 1)), "1x1");- assert_eq!(- ImageFormat::Png.dimensions(&png(1920, 1080)),- Some((1920, 1080))- );-}--#[test]-fn reads_jpeg_dimensions() {- assert_eq!(ImageFormat::Jpeg.dimensions(&jpeg(7, 5)), Some((7, 5)));-}--#[test]-fn truncated_headers_yield_none() {- assert_eq!(png_dimensions(&[0x89, 0x50, 0x4E, 0x47]), None);- assert_eq!(jpeg_dimensions(&[0xFF, 0xD8]), None);-}--#[test]-fn a_png_without_an_ihdr_chunk_yields_none() {- let mut bytes = png(4, 4);- bytes[12..16].copy_from_slice(b"XXXX");- assert_eq!(png_dimensions(&bytes), None);-}--#[test]-fn a_zero_dimension_yields_none() {- // Degenerate images cannot be placed aspect-correctly; they are rejected- // rather than divided by.- assert_eq!(png_dimensions(&png(0, 8)), None);- assert_eq!(png_dimensions(&png(8, 0)), None);- assert_eq!(jpeg_dimensions(&jpeg(0, 8)), None);- assert_eq!(jpeg_dimensions(&jpeg(8, 0)), None);-}--#[test]-fn a_jpeg_with_no_start_of_frame_yields_none() {- // SOI, then an APP0 segment and EOI — a valid marker stream carrying no- // frame header at all.- let bytes = vec![- 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00, 0xFF, 0xD9, 0x00, 0x00,- ];- assert_eq!(jpeg_dimensions(&bytes), None);-}--#[test]-fn a_jpeg_with_a_degenerate_segment_length_yields_none() {- // A declared segment length below the two length bytes themselves would- // make the walk loop forever if it were trusted.- let bytes = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x01, 0x00, 0x00, 0x00];- assert_eq!(jpeg_dimensions(&bytes), None);-}--#[test]-fn a_jpeg_skips_standalone_and_non_frame_markers_before_the_frame() {- // Restart markers and a DHT (0xC4, in the 0xCn range but not a frame- // header) must both be stepped over rather than mistaken for an SOF.- let mut bytes = vec![0xFF, 0xD8, 0xFF, 0xD0, 0xFF, 0xFF];- bytes.extend_from_slice(&[0xFF, 0xC4, 0x00, 0x04, 0x00, 0x00]); // DHT- bytes.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 0x08]);- bytes.extend_from_slice(&11u16.to_be_bytes()); // height- bytes.extend_from_slice(&22u16.to_be_bytes()); // width- bytes.extend_from_slice(&[0x03, 0x00, 0x00, 0x00, 0xFF, 0xD9]);- assert_eq!(jpeg_dimensions(&bytes), Some((22, 11)));-}--#[test]-fn a_jpeg_with_a_tem_marker_before_the_frame_is_still_measured() {- // TEM (0xFF01) carries no length field. Reading the next two bytes as one- // desynchronises the walk and rejects a valid file.- let mut bytes = vec![0xFF, 0xD8, 0xFF, 0x01];- bytes.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 0x08]);- bytes.extend_from_slice(&33u16.to_be_bytes()); // height- bytes.extend_from_slice(&44u16.to_be_bytes()); // width- bytes.extend_from_slice(&[0x03, 0x00, 0x00, 0x00, 0xFF, 0xD9]);- assert_eq!(jpeg_dimensions(&bytes), Some((44, 33)));-}--#[test]-fn format_renders_its_ooxml_name() {- assert_eq!(ImageFormat::Png.as_str(), "PNG");- assert_eq!(ImageFormat::Jpeg.as_str(), "JPEG");- assert_eq!(ImageFormat::Jpeg.to_string(), "JPEG");-}--#[test]-fn format_round_trips_through_json_as_its_ooxml_name() {- let json = serde_json::to_string(&ImageFormat::Png).expect("serialises");- assert_eq!(json, r#""PNG""#);- let back: ImageFormat = serde_json::from_str(&json).expect("deserialises");- assert_eq!(back, ImageFormat::Png);-}diff --git a/src/openhuman/tools/impl/document/format/spec/mod.rs b/src/openhuman/tools/impl/document/format/spec/mod.rsdeleted file mode 100644index 21f8a2eaeb..0000000000--- a/src/openhuman/tools/impl/document/format/spec/mod.rs+++ /dev/null@@ -1,45 +0,0 @@-//! The wire contracts: typed document specs and their validation, with no-//! dependency on any format writer.-//!-//! Every format module in this crate (`docx`, `pptx`, …) synthesises bytes from-//! a spec defined here. The split matters for two reasons:-//!-//! 1. **A host can share the contract without paying for the codec.** This-//! module is `serde` plus the crate [`Error`](crate::openhuman::tools::implementations::document::format::Error) — nothing else.-//! It is compiled in *every* build, including `--no-default-features`, so a-//! host whose synthesis happens elsewhere (in another process, or behind a-//! message bus) still gets the one authoritative definition of the spec-//! instead of re-declaring it and drifting.-//! 2. **Validation is cheap and belongs at the boundary.** The specs validate-//! themselves without touching a writer, so a host can reject a malformed-//! LLM tool call before paying for a blocking hop or a round trip.-//!-//! # Where things live-//!-//! - [`document`] — `.docx`: [`DocumentSpec`], [`DocumentSection`].-//! - [`presentation`] — `.pptx`: [`PresentationSpec`], [`SlideSpec`],-//! [`SlideImage`].-//! - [`image`] — [`ImageFormat`], for specs that embed raster images.-//!-//! **Types are re-exported here; limits are not.** Each format's limits stay-//! inside its own module, because the same name means a different thing in each-//! — `document::MAX_TEXT_CHARS` bounds a heading, `presentation::MAX_TEXT_CHARS`-//! bounds a bullet — and flattening them would put two distinct constants under-//! one name. Reach for `spec::presentation::MAX_SLIDES` and read it as the-//! sentence it is.-//!-//! The format modules re-export both the types and the limits they consume, so-//! `crate::openhuman::tools::implementations::document::format::docx::DocumentSpec` and [`crate::openhuman::tools::implementations::document::format::spec::DocumentSpec`] name the-//! same type.-//!-//! [`crate::openhuman::tools::implementations::document::format::spec::DocumentSpec`]: DocumentSpec--pub mod document;-pub mod image;-pub mod presentation;--pub use document::{DocumentSection, DocumentSpec};-pub use image::ImageFormat;-pub use presentation::wire::{WirePresentationSpec, WireSlideImage, WireSlideSpec};-#[allow(unused_imports)]-pub use presentation::{PresentationSpec, SlideImage, SlideSpec};diff --git a/src/openhuman/tools/impl/document/format/spec/presentation/mod.rs b/src/openhuman/tools/impl/document/format/spec/presentation/mod.rsdeleted file mode 100644index 9e030540cc..0000000000--- a/src/openhuman/tools/impl/document/format/spec/presentation/mod.rs+++ /dev/null@@ -1,340 +0,0 @@-//! The `.pptx` presentation spec: the typed description a caller hands to-//! `pptx::generate`, plus the size limits every spec is validated against.-//!-//! Same contract rules as [`crate::openhuman::tools::implementations::document::format::spec::document`] — `deny_unknown_fields`,-//! public limits, `validate` before synthesis — with one structural difference-//! worth understanding.-//!-//! # Images are bytes here, not references-//!-//! A [`SlideImage`] carries the image *bytes*, its format, and its native pixel-//! dimensions. It deliberately does **not** carry a path, a URL, or an-//! application-specific identifier, because resolving any of those is host-//! policy this crate has no business holding: which directories an agent may-//! read, whether a given identifier belongs to the caller, and whether fetching-//! a URL is an acceptable request to originate are all questions with different-//! answers in every host. A host resolves indirection under its own rules and-//! hands over the resulting bytes.-//!-//! [`SlideImage::from_bytes`] does the mechanical half of that hand-off:-//! identify the format and read the dimensions, or reject the bytes. It needs-//! no format writer, so a host can build and validate a whole spec in a build-//! with the `pptx` feature off.--use serde::{Deserialize, Serialize};--use crate::openhuman::tools::implementations::document::format::spec::image::ImageFormat;-use crate::openhuman::tools::implementations::document::format::{Error, Result};--/// Maximum number of content slides a single deck may contain.-///-/// Bounds generation time and output size; a caller with more material is-/// expected to split it across multiple decks.-pub const MAX_SLIDES: usize = 64;--/// Maximum length, in Unicode scalar values, of any single text field — the-/// deck title, the author byline, the theme hint, a slide title, a slide body,-/// one bullet, the speaker notes, or an image caption.-pub const MAX_TEXT_CHARS: usize = 2_000;--/// Maximum number of bullets on a single slide.-///-/// Higher counts produce a slide nobody can read, and bloat the output.-pub const MAX_BULLETS_PER_SLIDE: usize = 32;--/// Maximum number of images attached to a single slide.-///-/// The single-column layout stacks images vertically in the lower band of the-/// slide; past this count each one is too small to read.-pub const MAX_IMAGES_PER_SLIDE: usize = 6;--/// Maximum number of images across the whole deck.-///-/// Bounds the embedded media payload regardless of how the images are-/// distributed across slides.-pub const MAX_IMAGES_PER_DECK: usize = 8;--/// Maximum size, in bytes, of a single embedded image.-pub const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;--/// One image embedded on a slide.-///-/// Construct with [`SlideImage::from_bytes`] rather than by hand: it derives-/// `format` and the dimensions from the bytes, which keeps the three fields-/// consistent by construction. [`PresentationSpec::validate`] re-checks that-/// consistency, because a spec can also arrive over a wire.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct SlideImage {- /// The encoded image, as PNG or JPEG bytes.- pub bytes: Vec<u8>,- /// The format of `bytes`.- pub format: ImageFormat,- /// Native width in pixels, used to place the image without distorting it.- pub width_px: u32,- /// Native height in pixels, used to place the image without distorting it.- pub height_px: u32,- /// Optional caption, rendered as a bullet beneath the image.- #[serde(default)]- pub caption: Option<String>,-}--impl SlideImage {- /// Identify and measure `bytes`, producing a consistent [`SlideImage`].- ///- /// # Errors- ///- /// Returns [`Error::InvalidInput`] when `bytes` is empty, exceeds- /// [`MAX_IMAGE_BYTES`], is not PNG or JPEG, or carries a header this crate- /// cannot measure.- pub fn from_bytes(bytes: Vec<u8>, caption: Option<String>) -> Result<Self> {- if bytes.is_empty() {- return Err(Error::invalid_input("bytes", "must not be empty"));- }- if bytes.len() > MAX_IMAGE_BYTES {- return Err(Error::invalid_input(- "bytes",- format!("must be ≤ {MAX_IMAGE_BYTES} bytes"),- ));- }- let format = ImageFormat::sniff(&bytes)- .ok_or_else(|| Error::invalid_input("bytes", "must be a PNG or JPEG image"))?;- let (width_px, height_px) = format.dimensions(&bytes).ok_or_else(|| {- Error::invalid_input(- "bytes",- format!("{format} header is truncated or malformed"),- )- })?;- Ok(Self {- bytes,- format,- width_px,- height_px,- caption,- })- }-}--/// One content slide of the deck, rendered in spec order.-///-/// At least one of `title`, `body`, or `bullets` must carry renderable text.-/// Images alone are not enough — a slide holding only an image and no label-/// reads as a rendering bug rather than a design choice, and synthesis drops-/// blank text anyway.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct SlideSpec {- /// Slide title. May be blank for a visually minimal slide, as long as the- /// body or bullets carry text.- #[serde(default)]- pub title: String,- /// Body text, rendered above the bullets. Plain text only.- #[serde(default)]- pub body: Option<String>,- /// Bullets, rendered after the body text.- #[serde(default)]- pub bullets: Vec<String>,- /// Speaker notes attached to the slide.- #[serde(default)]- pub speaker_notes: Option<String>,- /// Images, stacked in a single column beneath the text.- #[serde(default)]- pub images: Vec<SlideImage>,-}--impl SlideSpec {- /// Returns `true` when the slide carries no renderable text at all — the- /// title, body, and every bullet are absent or blank.- ///- /// Synthesis trims and drops blank entries, so a slide holding only- /// `[" "]` would render without text despite carrying entries.- #[must_use]- pub fn is_textless(&self) -> bool {- let has_title = !self.title.trim().is_empty();- let has_body = self.body.as_deref().is_some_and(|b| !b.trim().is_empty());- let has_bullets = self.bullets.iter().any(|b| !b.trim().is_empty());- !(has_title || has_body || has_bullets)- }-}--/// A complete `.pptx` presentation spec.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct PresentationSpec {- /// Deck title, rendered on a leading title slide. Required and non-blank.- pub title: String,- /// Optional author byline, rendered beneath the deck title.- #[serde(default)]- pub author: Option<String>,- /// Optional theme hint.- ///- /// Accepted and validated but not yet acted on: synthesis uses the writer's- /// default template regardless. It is part of the contract so a host's tool- /// schema does not have to change when template selection lands.- #[serde(default)]- pub theme: Option<String>,- /// Content slides, in display order. Must contain at least one entry.- #[serde(default)]- pub slides: Vec<SlideSpec>,-}--impl PresentationSpec {- /// Total number of images across every slide.- #[must_use]- pub fn image_count(&self) -> usize {- self.slides- .iter()- .map(|slide| slide.images.len())- .sum::<usize>()- }-- /// Check the spec against every documented size limit, and check that each- /// image's declared format and dimensions match its bytes.- ///- /// Callers do not have to invoke this: `pptx::generate` validates before it- /// synthesises anything. It is public so a host can reject a malformed spec- /// at its own boundary — an LLM tool call, say — and hand back the- /// structured [`Error::InvalidInput`] before paying for a blocking hop, a- /// process boundary, or a bus round trip.- ///- /// # Errors- ///- /// Returns [`Error::InvalidInput`] naming the first field that violates a- /// limit. Fields are checked in spec order, so the reported field is stable- /// for a given spec.- pub fn validate(&self) -> Result<()> {- if self.title.trim().is_empty() {- return Err(Error::invalid_input("title", "must not be empty"));- }- Self::check_text_len("title", &self.title)?;- if let Some(author) = self.author.as_deref() {- Self::check_text_len("author", author)?;- }- if let Some(theme) = self.theme.as_deref() {- Self::check_text_len("theme", theme)?;- }- if self.slides.is_empty() {- return Err(Error::invalid_input(- "slides",- "must contain at least one slide",- ));- }- if self.slides.len() > MAX_SLIDES {- return Err(Error::invalid_input(- "slides",- format!("must contain ≤ {MAX_SLIDES} slides"),- ));- }- // Checked across the whole deck rather than per slide: the per-slide cap- // bounds readability, this one bounds the embedded media payload however- // the images are distributed.- if self.image_count() > MAX_IMAGES_PER_DECK {- return Err(Error::invalid_input(- "slides[].images",- format!("deck must contain ≤ {MAX_IMAGES_PER_DECK} images total"),- ));- }-- for (i, slide) in self.slides.iter().enumerate() {- if slide.is_textless() {- return Err(Error::invalid_input(- format!("slides[{i}]"),- "must have at least one of title / body / bullets",- ));- }- Self::check_text_len(format!("slides[{i}].title"), &slide.title)?;- if let Some(body) = slide.body.as_deref() {- Self::check_text_len(format!("slides[{i}].body"), body)?;- }- if slide.bullets.len() > MAX_BULLETS_PER_SLIDE {- return Err(Error::invalid_input(- format!("slides[{i}].bullets"),- format!("must contain ≤ {MAX_BULLETS_PER_SLIDE} bullets"),- ));- }- for (b, bullet) in slide.bullets.iter().enumerate() {- Self::check_text_len(format!("slides[{i}].bullets[{b}]"), bullet)?;- }- if let Some(notes) = slide.speaker_notes.as_deref() {- Self::check_text_len(format!("slides[{i}].speaker_notes"), notes)?;- }- if slide.images.len() > MAX_IMAGES_PER_SLIDE {- return Err(Error::invalid_input(- format!("slides[{i}].images"),- format!("must contain ≤ {MAX_IMAGES_PER_SLIDE} images"),- ));- }- for (m, image) in slide.images.iter().enumerate() {- Self::check_image(&format!("slides[{i}].images[{m}]"), image)?;- }- }- Ok(())- }-- /// Reject a text field longer than [`MAX_TEXT_CHARS`] scalar values.- fn check_text_len(field: impl Into<String>, value: &str) -> Result<()> {- if value.chars().count() > MAX_TEXT_CHARS {- return Err(Error::invalid_input(- field,- format!("must be ≤ {MAX_TEXT_CHARS} chars"),- ));- }- Ok(())- }-- /// Re-derive an image's format and dimensions from its bytes and reject any- /// disagreement with what the spec declares.- ///- /// [`SlideImage::from_bytes`] keeps the fields consistent by construction,- /// but a spec can also arrive as deserialized JSON, where the three fields- /// are independent. A declared format that does not match the bytes yields- /// a part the reader refuses to render, and declared dimensions that do not- /// match distort the image silently — both are worth a named rejection.- fn check_image(field: &str, image: &SlideImage) -> Result<()> {- if image.bytes.is_empty() {- return Err(Error::invalid_input(- format!("{field}.bytes"),- "must not be empty",- ));- }- if image.bytes.len() > MAX_IMAGE_BYTES {- return Err(Error::invalid_input(- format!("{field}.bytes"),- format!("must be ≤ {MAX_IMAGE_BYTES} bytes"),- ));- }- let sniffed = ImageFormat::sniff(&image.bytes).ok_or_else(|| {- Error::invalid_input(format!("{field}.bytes"), "must be a PNG or JPEG image")- })?;- if sniffed != image.format {- return Err(Error::invalid_input(- format!("{field}.format"),- format!("declared {} but the bytes are {sniffed}", image.format),- ));- }- let (width_px, height_px) = sniffed.dimensions(&image.bytes).ok_or_else(|| {- Error::invalid_input(- format!("{field}.bytes"),- format!("{sniffed} header is truncated or malformed"),- )- })?;- if (width_px, height_px) != (image.width_px, image.height_px) {- return Err(Error::invalid_input(- format!("{field}.width_px"),- format!(- "declared {}x{} but the bytes are {width_px}x{height_px}",- image.width_px, image.height_px- ),- ));- }- if let Some(caption) = image.caption.as_deref() {- Self::check_text_len(format!("{field}.caption"), caption)?;- }- Ok(())- }-}--pub mod wire;--#[cfg(test)]-mod test;diff --git a/src/openhuman/tools/impl/document/format/spec/presentation/test.rs b/src/openhuman/tools/impl/document/format/spec/presentation/test.rsdeleted file mode 100644index 9dcfef7fd3..0000000000--- a/src/openhuman/tools/impl/document/format/spec/presentation/test.rs+++ /dev/null@@ -1,367 +0,0 @@-//! Unit tests for the presentation wire contract.-//!-//! Format-independent, like the spec itself: these must pass in a build with-//! every format feature off.--#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]--use super::{- PresentationSpec, SlideImage, SlideSpec, MAX_BULLETS_PER_SLIDE, MAX_IMAGES_PER_DECK,- MAX_IMAGES_PER_SLIDE, MAX_IMAGE_BYTES, MAX_SLIDES, MAX_TEXT_CHARS,-};-use crate::openhuman::tools::implementations::document::format::spec::image::test::{jpeg, png};-use crate::openhuman::tools::implementations::document::format::spec::image::ImageFormat;-use crate::openhuman::tools::implementations::document::format::Error;--/// One valid slide carrying a title, a body, and a bullet.-fn slide() -> SlideSpec {- SlideSpec {- title: "Overview".to_string(),- body: Some("The situation so far.".to_string()),- bullets: vec!["A bullet".to_string()],- speaker_notes: Some("Keep it short.".to_string()),- images: vec![],- }-}--/// A minimal valid spec; each test mutates one field to drive a single branch.-fn spec() -> PresentationSpec {- PresentationSpec {- title: "Quarterly Review".to_string(),- author: Some("Alice".to_string()),- theme: Some("plain".to_string()),- slides: vec![slide()],- }-}--/// A valid image built from real header bytes.-fn image() -> SlideImage {- SlideImage::from_bytes(png(320, 200), Some("A chart".to_string())).expect("valid png")-}--/// Assert `spec` is rejected with an `InvalidInput` naming `field`.-fn assert_rejects(spec: &PresentationSpec, field: &str) {- match spec.validate() {- Err(Error::InvalidInput { field: f, .. }) => {- assert_eq!(f, field, "unexpected rejected field");- }- other => panic!("expected InvalidInput({field}), got {other:?}"),- }-}--#[test]-fn accepts_a_well_formed_spec() {- assert!(spec().validate().is_ok());-}--#[test]-fn accepts_a_spec_with_images() {- let mut s = spec();- s.slides[0].images = vec![image()];- assert!(s.validate().is_ok());-}--#[test]-fn rejects_a_blank_deck_title() {- let mut s = spec();- s.title = " ".to_string();- assert_rejects(&s, "title");-}--#[test]-fn rejects_over_long_deck_level_text() {- for (field, mutate) in [("title", 0), ("author", 1), ("theme", 2)] {- let mut s = spec();- let long = "x".repeat(MAX_TEXT_CHARS + 1);- match mutate {- 0 => s.title = long,- 1 => s.author = Some(long),- _ => s.theme = Some(long),- }- assert_rejects(&s, field);- }-}--#[test]-fn rejects_a_spec_with_no_slides() {- let mut s = spec();- s.slides.clear();- assert_rejects(&s, "slides");-}--#[test]-fn rejects_too_many_slides() {- let mut s = spec();- s.slides = vec![slide(); MAX_SLIDES + 1];- assert_rejects(&s, "slides");-}--#[test]-fn rejects_a_textless_slide() {- // Every text entry is present but whitespace-only, so synthesis would drop- // all of them and render an unlabelled slide.- let mut s = spec();- s.slides = vec![SlideSpec {- title: " ".to_string(),- body: Some("\t".to_string()),- bullets: vec![String::new()],- speaker_notes: None,- images: vec![],- }];- assert_rejects(&s, "slides[0]");-}--#[test]-fn rejects_a_slide_carrying_only_an_image() {- // Images do not satisfy the "must have text" rule: an unlabelled slide- // reads as a rendering bug rather than a design choice.- let mut s = spec();- s.slides = vec![SlideSpec {- title: String::new(),- body: None,- bullets: vec![],- speaker_notes: None,- images: vec![image()],- }];- assert_rejects(&s, "slides[0]");-}--#[test]-fn rejects_over_long_slide_text_naming_its_index() {- let long = || "x".repeat(MAX_TEXT_CHARS + 1);-- let mut s = spec();- s.slides.push(SlideSpec {- title: long(),- ..slide()- });- assert_rejects(&s, "slides[1].title");-- let mut s = spec();- s.slides[0].body = Some(long());- assert_rejects(&s, "slides[0].body");-- let mut s = spec();- s.slides[0].bullets = vec!["ok".to_string(), long()];- assert_rejects(&s, "slides[0].bullets[1]");-- let mut s = spec();- s.slides[0].speaker_notes = Some(long());- assert_rejects(&s, "slides[0].speaker_notes");-}--#[test]-fn rejects_too_many_bullets() {- let mut s = spec();- s.slides[0].bullets = vec!["b".to_string(); MAX_BULLETS_PER_SLIDE + 1];- assert_rejects(&s, "slides[0].bullets");-}--#[test]-fn rejects_too_many_images_on_one_slide() {- let mut s = spec();- s.slides[0].images = vec![image(); MAX_IMAGES_PER_SLIDE + 1];- assert_rejects(&s, "slides[0].images");-}--#[test]-fn rejects_too_many_images_across_the_deck() {- // Each slide is within the per-slide cap; only the deck total is not. The- // per-slide cap bounds readability, the deck cap bounds the media payload.- let per_slide = MAX_IMAGES_PER_SLIDE;- let slides_needed = MAX_IMAGES_PER_DECK / per_slide + 1;- let mut s = spec();- s.slides = vec![- SlideSpec {- images: vec![image(); per_slide],- ..slide()- };- slides_needed- ];- assert!(s.image_count() > MAX_IMAGES_PER_DECK);- assert_rejects(&s, "slides[].images");-}--#[test]-fn image_count_sums_across_slides() {- let mut s = spec();- s.slides = vec![- SlideSpec {- images: vec![image(), image()],- ..slide()- },- SlideSpec {- images: vec![image()],- ..slide()- },- ];- assert_eq!(s.image_count(), 3);-}--#[test]-fn rejects_an_over_long_image_caption() {- let mut s = spec();- let mut img = image();- img.caption = Some("c".repeat(MAX_TEXT_CHARS + 1));- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].caption");-}--#[test]-fn from_bytes_derives_format_and_dimensions() {- let img = SlideImage::from_bytes(png(1920, 1080), None).expect("valid png");- assert_eq!(img.format, ImageFormat::Png);- assert_eq!((img.width_px, img.height_px), (1920, 1080));- assert_eq!(img.caption, None);-- let img = SlideImage::from_bytes(jpeg(640, 480), Some("j".to_string())).expect("valid jpeg");- assert_eq!(img.format, ImageFormat::Jpeg);- assert_eq!((img.width_px, img.height_px), (640, 480));-}--#[test]-fn from_bytes_rejects_bad_input() {- assert!(matches!(- SlideImage::from_bytes(vec![], None),- Err(Error::InvalidInput { .. })- ));- assert!(matches!(- SlideImage::from_bytes(b"not an image".to_vec(), None),- Err(Error::InvalidInput { .. })- ));- // PNG signature with a truncated IHDR: the right format, unmeasurable.- assert!(matches!(- SlideImage::from_bytes(vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], None),- Err(Error::InvalidInput { .. })- ));-}--#[test]-fn from_bytes_rejects_an_oversize_image() {- // A real PNG header followed by enough filler to cross the cap, so the- // rejection is the size check rather than the sniff.- let mut bytes = png(8, 8);- bytes.resize(MAX_IMAGE_BYTES + 1, 0);- assert!(matches!(- SlideImage::from_bytes(bytes, None),- Err(Error::InvalidInput { .. })- ));-}--#[test]-fn validate_rejects_an_image_whose_declared_format_contradicts_its_bytes() {- // `from_bytes` cannot produce this, but deserialized JSON can: the three- // fields are independent on the wire. A wrong format yields a part the- // reader refuses to render, so it is worth a named rejection.- let mut s = spec();- let mut img = image();- img.format = ImageFormat::Jpeg;- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].format");-}--#[test]-fn validate_rejects_an_image_whose_declared_dimensions_contradict_its_bytes() {- // Declared dimensions that disagree with the bytes distort the image- // silently, which is worse than failing.- let mut s = spec();- let mut img = image();- img.width_px += 1;- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].width_px");-}--#[test]-fn validate_rejects_empty_oversize_and_unrecognised_image_bytes() {- let mut s = spec();- let mut img = image();- img.bytes.clear();- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].bytes");-- let mut s = spec();- let mut img = image();- img.bytes = b"not an image".to_vec();- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].bytes");-- let mut s = spec();- let mut img = image();- img.bytes.resize(MAX_IMAGE_BYTES + 1, 0);- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].bytes");-}--#[test]-fn validate_rejects_an_image_with_an_unmeasurable_header() {- // Sniffs as PNG, but the IHDR is gone — measurement fails after the format- // check has already passed, which is a distinct branch.- let mut s = spec();- let mut img = image();- img.bytes.truncate(8);- s.slides[0].images = vec![img];- assert_rejects(&s, "slides[0].images[0].bytes");-}--#[test]-fn is_textless_reflects_text_presence() {- assert!(!slide().is_textless());- assert!(SlideSpec {- title: String::new(),- body: None,- bullets: vec![],- speaker_notes: None,- images: vec![],- }- .is_textless());- // A title alone is enough.- assert!(!SlideSpec {- title: "Only a title".to_string(),- body: None,- bullets: vec![],- speaker_notes: None,- images: vec![],- }- .is_textless());- // So is a body alone, or a bullet alone.- assert!(!SlideSpec {- title: String::new(),- body: Some("Body".to_string()),- bullets: vec![],- speaker_notes: None,- images: vec![],- }- .is_textless());- assert!(!SlideSpec {- title: String::new(),- body: None,- bullets: vec!["Bullet".to_string()],- speaker_notes: None,- images: vec![],- }- .is_textless());-}--#[test]-fn spec_round_trips_through_json() {- let mut s = spec();- s.slides[0].images = vec![image()];- let json = serde_json::to_string(&s).expect("serialises");- let back: PresentationSpec = serde_json::from_str(&json).expect("deserialises");- assert_eq!(back, s);- assert!(back.validate().is_ok());-}--#[test]-fn spec_rejects_unknown_json_fields() {- let json = r#"{"title":"T","slides":[],"tilte":"typo"}"#;- assert!(serde_json::from_str::<PresentationSpec>(json).is_err());-}--#[test]-fn spec_defaults_optional_fields() {- let s: PresentationSpec = serde_json::from_str(r#"{"title":"T"}"#).expect("deserialises");- assert_eq!(s.author, None);- assert_eq!(s.theme, None);- assert!(s.slides.is_empty());-}diff --git a/src/openhuman/tools/impl/document/format/spec/presentation/wire.rs b/src/openhuman/tools/impl/document/format/spec/presentation/wire.rsdeleted file mode 100644index ef9cb8504c..0000000000--- a/src/openhuman/tools/impl/document/format/spec/presentation/wire.rs+++ /dev/null@@ -1,73 +0,0 @@-//! The presentation spec as it crosses a bus, where bytes cannot travel inline.-//!-//! A `TinyBus` frame is a 16 MiB JSON document and a deck may legally carry-//! 40 MiB of images, so image bytes ride a stream beside the call rather than-//! inside it. A call has one stream and a deck has many images, so the images-//! are concatenated in slide order and each one declares its `byte_len`; the-//! module splits them apart and resolves each into a real-//! [`super::SlideImage`] — bytes, format and dimensions.-//!-//! The lengths live in the spec rather than in the stream because they are what-//! makes a truncated or over-long transfer a named rejection instead of a deck-//! with a picture assembled from two different images.-//!-//! Only the presentation spec needs this treatment. A document spec is text and-//! its aggregate cap keeps it inside a frame, so a document crosses unchanged.-//!-//! Defined here rather than in the module that serves it so a host driving that-//! module over a bus shares one definition of the shape instead of re-declaring-//! it. Like the rest of [`crate::openhuman::tools::implementations::document::format::spec`] it is serde and nothing else.--use serde::{Deserialize, Serialize};--/// A slide image, as it appears on the bus: one byte range of the concatenated-/// image stream that travels beside the call.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct WireSlideImage {- /// Length of this image's bytes within the concatenated image stream.- pub byte_len: u64,- /// Optional caption, rendered as a bullet beneath the image.- #[serde(default)]- pub caption: Option<String>,-}--/// One content slide, as it appears on the bus.-///-/// Identical to [`super::SlideSpec`] apart from `images`.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct WireSlideSpec {- /// Slide title.- #[serde(default)]- pub title: String,- /// Body text, rendered above the bullets.- #[serde(default)]- pub body: Option<String>,- /// Bullets, rendered after the body text.- #[serde(default)]- pub bullets: Vec<String>,- /// Speaker notes attached to the slide.- #[serde(default)]- pub speaker_notes: Option<String>,- /// Images, each naming a staged blob.- #[serde(default)]- pub images: Vec<WireSlideImage>,-}--/// A deck, as it appears on the bus.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct WirePresentationSpec {- /// Deck title, rendered on a leading title slide.- pub title: String,- /// Optional author byline.- #[serde(default)]- pub author: Option<String>,- /// Optional theme hint.- #[serde(default)]- pub theme: Option<String>,- /// Content slides, in display order.- #[serde(default)]- pub slides: Vec<WireSlideSpec>,-}diff --git a/src/openhuman/tools/impl/document/mod.rs b/src/openhuman/tools/impl/document/mod.rsindex a221fc01ef..8e9f1f3fae 100644--- a/src/openhuman/tools/impl/document/mod.rs+++ b/src/openhuman/tools/impl/document/mod.rs@@ -39,7 +39,19 @@ use crate::openhuman::security::SecurityPolicy;use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};mod engine;-pub(crate) mod format;+/// The document wire contract, shared with the `tinydocs` module.+///+/// This was 1,873 lines of this repository — `format/error/`, `format/spec/` —+/// and every line of it also existed in `crates/tinydocs-bus/src/` upstream,+/// differing only in the paths inside doc links. Two definitions of a contract+/// is the drift risk the contract exists to remove: the specs here are what an+/// LLM is shown as a JSON tool schema and what the module validates against,+/// so a limit that moved on one side would become a tool description promising+/// something the module does not enforce.+///+/// Aliased rather than re-exported item by item so the ~30 existing+/// `…::document::format::…` paths keep resolving unchanged.+pub(crate) use tinydocs_bus as format;mod types;#[cfg(test)]