aimux_core/shared.rs
1//! Shared V4 value types used across all non-chat model traits.
2//!
3//! Aligned with Vercel AI SDK `SharedV4*` types
4//! (`reference/ai/packages/provider/src/shared/v4/`).
5//!
6//! These types are the common currency passed between the user-facing API and
7//! the provider-facing traits (`EmbeddingModel`, `ImageModel`, …). They are
8//! deliberately opaque to the core: providers read/write provider-specific
9//! keys inside them.
10
11use std::collections::HashMap;
12
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use tokio_util::sync::CancellationToken;
16use ts_rs::TS;
17
18// Re-export the existing `Warning` so providers can import everything they
19// need from `crate::shared` in one place.
20pub use crate::types::Warning;
21
22/// Additional HTTP headers sent with a provider request.
23///
24/// Aligned with V4 `SharedV4Headers` (`Record<string, string>`).
25pub type SharedHeaders = HashMap<String, String>;
26
27/// Additional provider-specific options (inputs), keyed by provider name.
28///
29/// The inner value is a JSON object whose keys are provider-specific option
30/// names. Aligned with V4 `SharedV4ProviderOptions`
31/// (`Record<string, JSONObject>`).
32///
33/// ```json
34/// { "anthropic": { "cacheControl": { "type": "ephemeral" } } }
35/// ```
36pub type SharedProviderOptions = HashMap<String, Value>;
37
38/// Additional provider-specific metadata (outputs), keyed by provider name.
39///
40/// Aligned with V4 `SharedV4ProviderMetadata` (`Record<string, JSONObject>`).
41pub type SharedProviderMetadata = HashMap<String, Value>;
42
43/// A mapping of provider names to provider-specific file identifiers.
44///
45/// Allows a logical file to be referenced across providers without
46/// re-uploading. Aligned with V4 `SharedV4ProviderReference`.
47///
48/// ```json
49/// { "openai": "file-abc123", "anthropic": "file-xyz789" }
50/// ```
51pub type SharedProviderReference = HashMap<String, String>;
52
53/// Either raw bytes or a base64-encoded string.
54///
55/// Providers should pass file data through without unnecessary conversion: if
56/// the upstream API returns base64, return [`FileBytes::Base64`]; if it
57/// returns binary, return [`FileBytes::Binary`].
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
59#[ts(export)]
60pub enum FileBytes {
61 /// Raw binary bytes.
62 Binary(Vec<u8>),
63 /// A base64-encoded string.
64 Base64(String),
65}
66
67/// File data as a tagged discriminated union.
68///
69/// Aligned with V4 `SharedV4FileData`.
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
71#[ts(export)]
72pub enum FileData {
73 /// Raw bytes (`Uint8Array`) or a base64-encoded string.
74 Data { data: FileBytes },
75 /// A URL that points to the file.
76 Url { url: String },
77 /// A provider reference (`{ [provider]: id }`).
78 Reference { reference: SharedProviderReference },
79 /// Inline text content (e.g. an inline text document).
80 Text { text: String },
81}
82
83/// A cancellation signal analogous to the Web `AbortSignal`.
84///
85/// Event-driven: backed by `tokio_util::sync::CancellationToken` (itself a
86/// `tokio::sync::Notify`). Consumers can poll [`is_aborted`](Self::is_aborted)
87/// synchronously, or await [`cancelled`](Self::cancelled) for prompt,
88/// notification-based wakeup — no polling loop needed.
89///
90/// This type is `Send + Sync` and cheap to clone.
91#[derive(Debug, Clone)]
92pub struct AbortSignal {
93 token: CancellationToken,
94}
95
96impl Default for AbortSignal {
97 fn default() -> Self {
98 Self::new()
99 }
100}
101
102impl AbortSignal {
103 /// Create a fresh, un-aborted signal.
104 pub fn new() -> Self {
105 Self {
106 token: CancellationToken::new(),
107 }
108 }
109
110 /// Request cancellation. All clones observe the aborted state and any
111 /// pending [`cancelled`](Self::cancelled) futures resolve.
112 pub fn abort(&self) {
113 self.token.cancel();
114 }
115
116 /// Returns `true` once [`abort`](Self::abort) has been called.
117 pub fn is_aborted(&self) -> bool {
118 self.token.is_cancelled()
119 }
120
121 /// A future that resolves as soon as the signal is aborted.
122 ///
123 /// If the signal is already aborted, the future resolves immediately on
124 /// the first poll. Suitable for `tokio::select!` arms.
125 pub fn cancelled(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
126 let token = self.token.clone();
127 async move { token.cancelled_owned().await }
128 }
129}
130
131/// Image/video size in `{width}x{height}` format (e.g. `"1024x1024"`).
132///
133/// Newtype that enforces the `WxH` format used by V4 image `size` and video
134/// `resolution` options. Aligned with the TS template-literal type
135/// `` `${number}x${number}` ``.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
137#[ts(export)]
138pub struct Size {
139 width: u32,
140 height: u32,
141}
142
143impl Size {
144 /// Create a size from explicit pixel dimensions.
145 pub const fn new(width: u32, height: u32) -> Self {
146 Self { width, height }
147 }
148
149 /// Parse a `{width}x{height}` string (e.g. `"1280x720"`).
150 ///
151 /// Returns an error if the string is not in the expected format or either
152 /// dimension is zero.
153 pub fn parse(s: &str) -> Result<Self, String> {
154 let (w, h) = parse_pair(s, 'x').ok_or_else(|| {
155 format!("invalid size `{s}`: expected format `{{width}}x{{height}}` (e.g. `1024x1024`)")
156 })?;
157 if w == 0 || h == 0 {
158 return Err(format!("invalid size `{s}`: width and height must be > 0"));
159 }
160 Ok(Self::new(w, h))
161 }
162
163 /// Width in pixels.
164 pub const fn width(&self) -> u32 {
165 self.width
166 }
167
168 /// Height in pixels.
169 pub const fn height(&self) -> u32 {
170 self.height
171 }
172}
173
174impl std::fmt::Display for Size {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 write!(f, "{}x{}", self.width, self.height)
177 }
178}
179
180impl std::str::FromStr for Size {
181 type Err = String;
182 fn from_str(s: &str) -> Result<Self, Self::Err> {
183 Self::parse(s)
184 }
185}
186
187/// Aspect ratio in `{width}:{height}` format (e.g. `"16:9"`).
188///
189/// Newtype that enforces the `W:H` format used by V4 image and video
190/// `aspectRatio` options. Aligned with the TS template-literal type
191/// `` `${number}:${number}` ``.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
193#[ts(export)]
194pub struct AspectRatio {
195 width: u32,
196 height: u32,
197}
198
199impl AspectRatio {
200 /// Create an aspect ratio from explicit components.
201 pub const fn new(width: u32, height: u32) -> Self {
202 Self { width, height }
203 }
204
205 /// Parse a `{width}:{height}` string (e.g. `"16:9"`).
206 pub fn parse(s: &str) -> Result<Self, String> {
207 let (w, h) = parse_pair(s, ':').ok_or_else(|| {
208 format!(
209 "invalid aspect ratio `{s}`: expected format `{{width}}:{{height}}` (e.g. `16:9`)"
210 )
211 })?;
212 if w == 0 || h == 0 {
213 return Err(format!(
214 "invalid aspect ratio `{s}`: width and height must be > 0"
215 ));
216 }
217 Ok(Self::new(w, h))
218 }
219
220 /// Width component.
221 pub const fn width(&self) -> u32 {
222 self.width
223 }
224
225 /// Height component.
226 pub const fn height(&self) -> u32 {
227 self.height
228 }
229}
230
231impl std::fmt::Display for AspectRatio {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 write!(f, "{}:{}", self.width, self.height)
234 }
235}
236
237impl std::str::FromStr for AspectRatio {
238 type Err = String;
239 fn from_str(s: &str) -> Result<Self, Self::Err> {
240 Self::parse(s)
241 }
242}
243
244/// Parse a `{a}{sep}{b}` pair of unsigned integers.
245fn parse_pair(s: &str, sep: char) -> Option<(u32, u32)> {
246 let (a, b) = s.split_once(sep)?;
247 let a: u32 = a.trim().parse().ok()?;
248 let b: u32 = b.trim().parse().ok()?;
249 Some((a, b))
250}
251
252/// Response information for telemetry and debugging.
253///
254/// Aligned with the `response` object that appears on most V4 model results.
255/// All fields are optional because different providers populate different
256/// subsets; traits whose TS spec marks `response` as required use
257/// `ResponseInfo` directly, while those that mark it optional use
258/// `Option<ResponseInfo>`.
259#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
260#[ts(export)]
261pub struct ResponseInfo {
262 /// Timestamp for the start of the generated response (ISO 8601 string).
263 pub timestamp: Option<String>,
264 /// The ID of the model that was used to generate the response.
265 pub model_id: Option<String>,
266 /// Response headers.
267 pub headers: Option<SharedHeaders>,
268 /// The response body (opaque JSON).
269 pub body: Option<Value>,
270}
271
272/// Optional request information for telemetry and debugging.
273///
274/// Aligned with the `request?` object that appears on some V4 model results.
275#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
276#[ts(export)]
277pub struct RequestInfo {
278 /// The request body that was sent (opaque JSON).
279 pub body: Option<Value>,
280}