//! Story 3.16 (FR-18): pure composition of a Prompt with its pinned Resource dependencies. //! //! One renderer serves the admin preview and MCP `prompts/get`: the accepted typed renderer //! (`PromptDefinition::preview`) validates arguments and renders the template text first, then the //! pinned content of every declared `resource_refs` index is appended to the message the author //! declared. Message count, order and roles come from the published template only — dependency //! content can never add, remove or re-role a message. There is no tool dispatch and no code path //! that interprets dependency content, so a `{"tool_calls": …}` block stays inert text. //! //! Failures are typed and total: the caller receives a reason and a position/source path, never a //! partially composed message list and never the matched secret text. use serde_json::{Map, Value}; use crate::prompt::{ MAX_TEXT_BYTES, PromptDefinition, PromptError, PromptMessage, PromptSensitivity, }; use crate::resource::{ResourceKind, publication_include_directives, publication_secret_findings}; /// Bound of the `dependencies` array (contract §1, `MAX_PROMPT_DEPENDENCIES`). pub const MAX_PROMPT_DEPENDENCIES: usize = 16; /// Wire values of `dependencies[i].source_class` (contract §4). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PromptDependencySourceClass { Static, Dynamic, } impl PromptDependencySourceClass { pub fn as_str(self) -> &'static str { match self { Self::Static => "static", Self::Dynamic => "dynamic", } } pub fn parse(value: &str) -> Option { match value { "static" => Some(Self::Static), "dynamic" => Some(Self::Dynamic), _ => None, } } } /// One resolved pin of a published dependency: the exact version the Prompt was published with, /// plus the metadata the provenance block reports. It carries no content. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PromptDependencyPin { pub position: usize, pub resource_id: String, pub version: u32, pub digest: String, pub kind: ResourceKind, pub mime_type: String, pub source_class: PromptDependencySourceClass, pub sensitivity: PromptSensitivity, } impl PromptDependencyPin { /// Provenance row of the preview contract (§7): declaration order, no content. pub fn provenance_json(pin: &Self) -> Value { serde_json::json!({ "position": pin.position, "resource_id": pin.resource_id, "version": pin.version, "digest": pin.digest, "kind": pin.kind.as_str(), "mime_type": pin.mime_type, "source_class": pin.source_class.as_str(), "sensitivity": pin.sensitivity, }) } } /// Ordered provenance block of a composed result. pub fn provenance_json(pins: &[PromptDependencyPin]) -> Vec { pins.iter() .map(PromptDependencyPin::provenance_json) .collect() } /// Typed refusal of the composition boundary. #[derive(Clone, Debug, PartialEq, Eq)] pub enum PromptCompositionError { /// A dependency no message references: pinning content that is never delivered (contract §1). DependencyUnused { position: usize, resource_id: String, version: u32, }, /// The pinned exact version cannot be resolved/read right now (revoked, archived, foreign). DependencyUnavailable { position: usize }, /// `binary` has no negotiated message representation (contract §4). DependencyRepresentationUnsupported { position: usize }, /// The template text itself carries a raw credential. CredentialFinding { source_path: String }, /// The template text itself carries an explicit `include:` access-bypass directive. AccessBypassFinding { source_path: String }, /// Read-time content of a dynamic dependency carries a raw credential. DependencyCredentialFinding { position: usize }, /// Read-time content of a dynamic dependency carries an `include:` directive. DependencyAccessBypassFinding { position: usize }, /// The accepted renderer refused the template/arguments. Template(PromptError), } impl From for PromptCompositionError { fn from(error: PromptError) -> Self { Self::Template(error) } } /// Strictest-sensitivity fold: `effective = max(local, every pinned dependency)` (contract §3). pub fn effective_sensitivity( local: PromptSensitivity, pins: &[PromptDependencyPin], ) -> PromptSensitivity { pins.iter().fold(local, |strictest, pin| { if rank(pin.sensitivity) > rank(strictest) { pin.sensitivity } else { strictest } }) } fn rank(sensitivity: PromptSensitivity) -> u8 { match sensitivity { PromptSensitivity::Public => 0, PromptSensitivity::Internal => 1, PromptSensitivity::Secret => 2, } } /// The first dependency (declaration order) that no message references. pub fn unused_dependency(definition: &PromptDefinition) -> Option { (0..definition.dependencies().len()).find(|position| { !definition .messages() .iter() .any(|message| message.resource_refs.contains(position)) }) } /// Bounded scan of the Prompt template text (messages, contract §5). pub fn scan_template(definition: &PromptDefinition) -> Result<(), PromptCompositionError> { for (position, message) in definition.messages().iter().enumerate() { let bytes = message.content.as_bytes(); if publication_secret_findings(bytes).is_some() { return Err(PromptCompositionError::CredentialFinding { source_path: format!("messages[{position}].content"), }); } if !publication_include_directives(bytes).is_empty() { return Err(PromptCompositionError::AccessBypassFinding { source_path: format!("messages[{position}].content"), }); } } Ok(()) } /// Bounded scan of dynamic dependency content, fetched at read time (contract §5). pub fn scan_dependency_content( position: usize, bytes: &[u8], ) -> Result<(), PromptCompositionError> { if publication_secret_findings(bytes).is_some() { return Err(PromptCompositionError::DependencyCredentialFinding { position }); } if !publication_include_directives(bytes).is_empty() { return Err(PromptCompositionError::DependencyAccessBypassFinding { position }); } Ok(()) } /// Content of every dependency, indexed by declaration position. /// /// `None` means the exact pinned version could not be read now; a dependency that is absent from /// this slice is treated the same way, so composition is total and never silently short. pub fn render( definition: &PromptDefinition, pins: &[PromptDependencyPin], arguments: &Map, contents: &[Option>], ) -> Result, PromptCompositionError> { let mut messages = definition.preview(arguments)?; for message in &mut messages { for index in &message.resource_refs { let Some(Some(bytes)) = contents.get(*index) else { return Err(PromptCompositionError::DependencyUnavailable { position: *index }); }; let pin = pins .iter() .find(|pin| pin.position == *index) .ok_or(PromptCompositionError::DependencyUnavailable { position: *index })?; let text = match pin.kind { ResourceKind::Text | ResourceKind::Json => { std::str::from_utf8(bytes).map_err(|_| { PromptCompositionError::DependencyRepresentationUnsupported { position: *index, } })? } ResourceKind::Binary => { return Err( PromptCompositionError::DependencyRepresentationUnsupported { position: *index, }, ); } }; // Contract §5: dynamic content is fetched at read time and was never scanned at // publication, so it is scanned here — one call site for preview and `prompts/get`. if pin.source_class == PromptDependencySourceClass::Dynamic { scan_dependency_content(*index, text.as_bytes())?; } if !message.content.is_empty() { message.content.push_str("\n\n"); } message.content.push_str(text); // shortcut: one composed message keeps the accepted 16 KiB text bound; a larger // composed message is refused instead of silently truncated. if message.content.len() > MAX_TEXT_BYTES { return Err(PromptCompositionError::Template( PromptError::InvalidTemplate, )); } } } Ok(messages) }