Skip to main content

base/interface/
prompt_middleware.rs

1//! `PromptMiddleware` — what an embedding program says about a user message
2//! before it enters the conversation.
3//!
4//! The Rust counterpart of a `UserPromptSubmit` hook, for rules that live in
5//! the embedder's own code: it sees every user message, the one that opens a
6//! turn and the ones steered into a running turn at a step boundary, and lets
7//! it through, rewrites it, or refuses it. It runs after the hooks configured
8//! in settings, in the order the middlewares were added, so the embedder's
9//! rules are the last word: nothing configured can rewrite back what they
10//! decided.
11//!
12//! Attachments that came with the message are shown read-only through
13//! `inspect_with_attachments`; a middleware that only implements `inspect`
14//! never sees them.
15
16use async_trait::async_trait;
17
18use crate::permission::PermissionMode;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum PromptDelivery {
22    /// The message opens a turn.
23    Turn,
24    /// The message joins the running turn at a step boundary.
25    Steer,
26}
27
28impl PromptDelivery {
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::Turn => "turn",
32            Self::Steer => "steer",
33        }
34    }
35}
36
37#[derive(Debug, Clone)]
38pub struct PromptCall<'a> {
39    pub session_id: &'a str,
40    pub turn_id: &'a str,
41    pub content: &'a str,
42    pub delivery: PromptDelivery,
43    pub permission_mode: PermissionMode,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum PromptDecision {
48    Continue,
49    Rewrite(String),
50    /// A turn ends as a `UserPromptSubmit` block ends it (`stopped_by_hook`,
51    /// no model call); a steered message is left out and the turn goes on.
52    Block {
53        message: Option<String>,
54    },
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum PromptAttachmentKind {
59    /// A path the runtime reads after screening; its content is not read
60    /// for the middleware.
61    File,
62    /// Text the host already read.
63    Text,
64    /// An image the host already decoded.
65    Image,
66    /// A document the host already encoded.
67    Document,
68}
69
70impl PromptAttachmentKind {
71    pub fn as_str(self) -> &'static str {
72        match self {
73            Self::File => "file",
74            Self::Text => "text",
75            Self::Image => "image",
76            Self::Document => "document",
77        }
78    }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct PromptAttachment<'a> {
84    pub kind: PromptAttachmentKind,
85    pub name: Option<&'a str>,
86    pub media_type: Option<&'a str>,
87    /// Bytes: the file's length on disk, the text's UTF-8 length, the
88    /// image's decoded length. `None` when a file's metadata can't be read.
89    pub size: Option<u64>,
90    pub text: Option<&'a str>,
91}
92
93impl<'a> PromptAttachment<'a> {
94    pub fn file(path: &'a str, media_type: Option<&'a str>, size: Option<u64>) -> Self {
95        Self {
96            kind: PromptAttachmentKind::File,
97            name: Some(path),
98            media_type,
99            size,
100            text: None,
101        }
102    }
103
104    pub fn text(name: &'a str, content: &'a str) -> Self {
105        Self {
106            kind: PromptAttachmentKind::Text,
107            name: Some(name),
108            media_type: None,
109            size: Some(content.len() as u64),
110            text: Some(content),
111        }
112    }
113
114    pub fn document(name: Option<&'a str>, media_type: &'a str, size: u64) -> Self {
115        Self {
116            kind: PromptAttachmentKind::Document,
117            name,
118            media_type: Some(media_type),
119            size: Some(size),
120            text: None,
121        }
122    }
123
124    pub fn image(media_type: &'a str, size: u64) -> Self {
125        Self {
126            kind: PromptAttachmentKind::Image,
127            name: None,
128            media_type: Some(media_type),
129            size: Some(size),
130            text: None,
131        }
132    }
133}
134
135#[async_trait]
136pub trait PromptMiddleware: Send + Sync {
137    async fn inspect(&self, call: &PromptCall<'_>) -> PromptDecision;
138
139    /// What the runtime calls. Attachments can't be rewritten: a `Rewrite`
140    /// replaces the text only, a `Block` refuses the whole message.
141    async fn inspect_with_attachments(
142        &self,
143        call: &PromptCall<'_>,
144        attachments: &[PromptAttachment<'_>],
145    ) -> PromptDecision {
146        let _ = attachments;
147        self.inspect(call).await
148    }
149}