Skip to main content

fm_rs/
model.rs

1//! `SystemLanguageModel`, `TokenUsage`, and `ModelAvailability` types.
2
3use std::ffi::{CStr, CString};
4use std::ptr::{self, NonNull};
5use std::sync::Arc;
6#[cfg(feature = "private-cloud-compute")]
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use crate::error::{Error, Result, ToolCallError};
10use crate::ffi::{self, AvailabilityCode, SwiftPtr};
11use crate::tool::{Tool, tools_to_json};
12
13const TOKEN_USAGE_UNAVAILABLE_SENTINEL: i64 = -2;
14const TOKEN_ESTIMATE_CHARS_PER_TOKEN: usize = 4;
15
16/// Represents the availability status of a `FoundationModel`.
17#[non_exhaustive]
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ModelAvailability {
20    /// Model is available and ready to use.
21    Available,
22    /// Device is not eligible for Apple Intelligence.
23    DeviceNotEligible,
24    /// Apple Intelligence is not enabled in system settings.
25    AppleIntelligenceNotEnabled,
26    /// Model is not ready (downloading or other system reasons).
27    ModelNotReady,
28    /// Private Cloud Compute isn't ready to serve requests.
29    PrivateCloudComputeSystemNotReady,
30    /// Unavailability for an unknown reason.
31    Unknown,
32}
33
34impl ModelAvailability {
35    /// Returns an error describing why the model is unavailable.
36    pub fn into_error(self) -> Option<Error> {
37        match self {
38            ModelAvailability::Available => None,
39            ModelAvailability::DeviceNotEligible => Some(Error::DeviceNotEligible),
40            ModelAvailability::AppleIntelligenceNotEnabled => {
41                Some(Error::AppleIntelligenceNotEnabled)
42            }
43            ModelAvailability::ModelNotReady => Some(Error::ModelNotReady),
44            ModelAvailability::PrivateCloudComputeSystemNotReady => {
45                Some(Error::PrivateCloudComputeSystemNotReady)
46            }
47            ModelAvailability::Unknown => Some(Error::ModelNotAvailable),
48        }
49    }
50}
51
52impl From<AvailabilityCode> for ModelAvailability {
53    fn from(code: AvailabilityCode) -> Self {
54        match code {
55            AvailabilityCode::Available => ModelAvailability::Available,
56            AvailabilityCode::DeviceNotEligible => ModelAvailability::DeviceNotEligible,
57            AvailabilityCode::AppleIntelligenceNotEnabled => {
58                ModelAvailability::AppleIntelligenceNotEnabled
59            }
60            AvailabilityCode::ModelNotReady => ModelAvailability::ModelNotReady,
61            AvailabilityCode::PrivateCloudComputeSystemNotReady => {
62                ModelAvailability::PrivateCloudComputeSystemNotReady
63            }
64            AvailabilityCode::Unknown => ModelAvailability::Unknown,
65        }
66    }
67}
68
69mod private {
70    pub trait Sealed {}
71}
72
73/// A Foundation Models implementation that can create a [`crate::Session`].
74///
75/// This sealed abstraction supports both the on-device model and model types
76/// introduced by newer Apple SDKs without allowing invalid external FFI
77/// implementations.
78pub trait LanguageModel: private::Sealed + Send + Sync {
79    /// Returns the opaque Swift model box used by the FFI layer.
80    #[doc(hidden)]
81    fn raw_model_ptr(&self) -> *mut std::ffi::c_void;
82
83    /// Checks whether the model is currently available.
84    fn is_available(&self) -> bool {
85        unsafe { ffi::fm_model_is_available(self.raw_model_ptr()) }
86    }
87
88    /// Returns the current reason-specific model availability.
89    fn availability(&self) -> ModelAvailability {
90        let code = unsafe { ffi::fm_model_availability(self.raw_model_ptr()) };
91        AvailabilityCode::from(code).into()
92    }
93
94    /// Returns a reason-specific error if the model is unavailable.
95    fn ensure_available(&self) -> Result<()> {
96        match self.availability().into_error() {
97            Some(err) => Err(err),
98            None => Ok(()),
99        }
100    }
101
102    /// Returns the model context window size in tokens.
103    ///
104    /// For the on-device model this is reported synchronously (26.4+ build
105    /// SDK required); for Private Cloud Compute it performs a network
106    /// request and can fail with [`Error::NetworkFailure`] or
107    /// [`Error::ServiceUnavailable`].
108    fn context_size(&self) -> Result<u64> {
109        let mut error: SwiftPtr = ptr::null_mut();
110        let size = unsafe { ffi::fm_model_context_size(self.raw_model_ptr(), &raw mut error) };
111
112        if !error.is_null() {
113            return Err(error_from_swift(error));
114        }
115
116        u64::try_from(size).map_err(|_| {
117            Error::InternalError(format!("Context size returned invalid value {size}"))
118        })
119    }
120}
121
122struct ModelHandle {
123    ptr: NonNull<std::ffi::c_void>,
124}
125
126impl ModelHandle {
127    fn from_ffi(ptr: SwiftPtr, error: SwiftPtr, model_name: &str) -> Result<Self> {
128        if !error.is_null() {
129            return Err(error_from_swift(error));
130        }
131
132        NonNull::new(ptr).map(|ptr| Self { ptr }).ok_or_else(|| {
133            Error::InternalError(format!(
134                "{model_name} creation returned null without an error"
135            ))
136        })
137    }
138
139    fn as_ptr(&self) -> SwiftPtr {
140        self.ptr.as_ptr()
141    }
142}
143
144impl Drop for ModelHandle {
145    fn drop(&mut self) {
146        unsafe {
147            ffi::fm_model_free(self.ptr.as_ptr());
148        }
149    }
150}
151
152// SAFETY: ModelHandle owns an immutable Swift language-model box. Foundation
153// Models declares its concrete model implementations Sendable, and all mutable
154// session state is stored in separate LanguageModelSession instances.
155unsafe impl Send for ModelHandle {}
156unsafe impl Sync for ModelHandle {}
157
158/// The system language model provided by Apple Intelligence.
159///
160/// This is the main entry point for using on-device AI capabilities.
161/// Use [`SystemLanguageModel::new()`] to get the default model.
162///
163/// # Example
164///
165/// ```rust,no_run
166/// use fm_rs::SystemLanguageModel;
167///
168/// let model = SystemLanguageModel::new()?;
169/// if model.is_available() {
170///     println!("Model is ready to use!");
171/// }
172/// # Ok::<(), fm_rs::Error>(())
173/// ```
174pub struct SystemLanguageModel {
175    handle: ModelHandle,
176}
177
178/// Token usage returned by `SystemLanguageModel` 26.4+ APIs.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct TokenUsage {
181    /// Number of tokens, either measured by the framework tokenizer or
182    /// estimated locally (see [`estimated`](Self::estimated)).
183    pub token_count: usize,
184    /// Whether `token_count` is a local chars-per-token estimate rather than
185    /// a framework tokenizer measurement.
186    ///
187    /// `true` when the build SDK or runtime lacks the token-usage APIs and
188    /// the count was derived heuristically (~4 characters per token).
189    pub estimated: bool,
190}
191
192impl SystemLanguageModel {
193    /// Creates the default system language model.
194    ///
195    /// Construction does not check whether the model is currently available;
196    /// call [`ensure_available`](Self::ensure_available) when availability is
197    /// required before creating a session.
198    pub fn new() -> Result<Self> {
199        let mut error: SwiftPtr = ptr::null_mut();
200
201        let ptr = unsafe { ffi::fm_model_default(&raw mut error) };
202
203        ModelHandle::from_ffi(ptr, error, "SystemLanguageModel").map(|handle| Self { handle })
204    }
205
206    /// Returns a raw pointer to the underlying Swift object.
207    ///
208    /// This is used internally for FFI calls.
209    pub(crate) fn as_ptr(&self) -> SwiftPtr {
210        self.handle.as_ptr()
211    }
212
213    /// Checks if the model is available for use.
214    ///
215    /// Returns `true` if the model is available and ready to generate responses.
216    pub fn is_available(&self) -> bool {
217        LanguageModel::is_available(self)
218    }
219
220    /// Gets the current availability status of the model.
221    ///
222    /// This provides more detailed information about why the model might not be available.
223    pub fn availability(&self) -> ModelAvailability {
224        LanguageModel::availability(self)
225    }
226
227    /// Returns a reason-specific error if the model is unavailable.
228    pub fn ensure_available(&self) -> Result<()> {
229        LanguageModel::ensure_available(self)
230    }
231
232    /// Returns the on-device context window size in tokens.
233    ///
234    /// Requires building with the macOS/iOS 26.4 SDK or later; older build
235    /// SDKs return [`Error::UnsupportedPlatform`]. On pre-27 runtimes the
236    /// system reports the back-deployed default of 4096 tokens.
237    pub fn context_size(&self) -> Result<u64> {
238        LanguageModel::context_size(self)
239    }
240
241    /// Returns token usage for a prompt.
242    ///
243    /// Uses platform token-usage APIs when available in both the build SDK and runtime.
244    /// Otherwise returns a heuristic estimate.
245    pub fn token_usage_for(&self, prompt: &str) -> Result<TokenUsage> {
246        let prompt_c = CString::new(prompt)?;
247        let mut error: SwiftPtr = ptr::null_mut();
248
249        let token_count = unsafe {
250            ffi::fm_model_token_usage_for(self.as_ptr(), prompt_c.as_ptr(), &raw mut error)
251        };
252
253        if !error.is_null() {
254            return Err(error_from_swift(error));
255        }
256
257        if token_count == TOKEN_USAGE_UNAVAILABLE_SENTINEL {
258            return Ok(TokenUsage {
259                token_count: crate::context::estimate_tokens(
260                    prompt,
261                    TOKEN_ESTIMATE_CHARS_PER_TOKEN,
262                ),
263                estimated: true,
264            });
265        }
266
267        token_usage_from_raw(token_count)
268    }
269
270    /// Returns token usage for session instructions and tool definitions.
271    ///
272    /// Tool definitions are serialized from the Rust [`Tool`] trait objects.
273    /// Uses platform token-usage APIs when available in both the build SDK and runtime.
274    /// Otherwise returns a heuristic estimate.
275    pub fn token_usage_for_tools(
276        &self,
277        instructions: &str,
278        tools: &[Arc<dyn Tool>],
279    ) -> Result<TokenUsage> {
280        let instructions_c = CString::new(instructions)?;
281        let tools_json = if tools.is_empty() {
282            None
283        } else {
284            let tool_refs: Vec<&dyn Tool> = tools.iter().map(std::convert::AsRef::as_ref).collect();
285            Some(CString::new(tools_to_json(&tool_refs)?)?)
286        };
287        let tools_ptr = tools_json.as_ref().map_or(ptr::null(), |s| s.as_ptr());
288
289        let mut error: SwiftPtr = ptr::null_mut();
290        let token_count = unsafe {
291            ffi::fm_model_token_usage_for_tools(
292                self.as_ptr(),
293                instructions_c.as_ptr(),
294                tools_ptr,
295                &raw mut error,
296            )
297        };
298
299        if !error.is_null() {
300            return Err(error_from_swift(error));
301        }
302
303        if token_count == TOKEN_USAGE_UNAVAILABLE_SENTINEL {
304            let fallback =
305                crate::context::estimate_tokens(instructions, TOKEN_ESTIMATE_CHARS_PER_TOKEN)
306                    + tools_json.as_ref().map_or(0, |json| {
307                        crate::context::estimate_tokens(
308                            &json.to_string_lossy(),
309                            TOKEN_ESTIMATE_CHARS_PER_TOKEN,
310                        )
311                    });
312            return Ok(TokenUsage {
313                token_count: fallback,
314                estimated: true,
315            });
316        }
317
318        token_usage_from_raw(token_count)
319    }
320}
321
322impl private::Sealed for SystemLanguageModel {}
323
324impl LanguageModel for SystemLanguageModel {
325    fn raw_model_ptr(&self) -> *mut std::ffi::c_void {
326        self.as_ptr()
327    }
328}
329
330impl std::fmt::Debug for SystemLanguageModel {
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332        f.debug_struct("SystemLanguageModel")
333            .field("availability", &self.availability())
334            .finish()
335    }
336}
337
338/// Apple Foundation Models running on Private Cloud Compute.
339///
340/// This model requires a 27.0-or-newer Apple platform, network access, an
341/// Apple Intelligence-capable device, and Apple's managed
342/// `com.apple.developer.private-cloud-compute` entitlement authorized by the
343/// app's provisioning profile. Construction on an older SDK or runtime returns
344/// [`Error::UnsupportedPlatform`].
345#[cfg(feature = "private-cloud-compute")]
346pub struct PrivateCloudComputeLanguageModel {
347    handle: ModelHandle,
348}
349
350#[cfg(feature = "private-cloud-compute")]
351impl PrivateCloudComputeLanguageModel {
352    /// Creates the Private Cloud Compute language model.
353    pub fn new() -> Result<Self> {
354        let mut error: SwiftPtr = ptr::null_mut();
355        let ptr = unsafe { ffi::fm_model_private_cloud_compute(&raw mut error) };
356
357        ModelHandle::from_ffi(ptr, error, "PrivateCloudComputeLanguageModel")
358            .map(|handle| Self { handle })
359    }
360
361    /// Checks whether PCC is currently available.
362    pub fn is_available(&self) -> bool {
363        LanguageModel::is_available(self)
364    }
365
366    /// Returns the current reason-specific PCC availability.
367    pub fn availability(&self) -> ModelAvailability {
368        LanguageModel::availability(self)
369    }
370
371    /// Returns a reason-specific error if PCC is unavailable.
372    pub fn ensure_available(&self) -> Result<()> {
373        LanguageModel::ensure_available(self)
374    }
375
376    /// Returns the user's current Private Cloud Compute quota usage.
377    ///
378    /// Apple applies a daily, per-user iCloud quota; check this before
379    /// sending requests to decide whether to fall back to the on-device
380    /// [`crate::SystemLanguageModel`].
381    pub fn quota_usage(&self) -> Result<QuotaUsage> {
382        let mut error: SwiftPtr = ptr::null_mut();
383        let json_ptr = unsafe { ffi::fm_model_pcc_quota_usage(self.as_ptr(), &raw mut error) };
384
385        if !error.is_null() {
386            return Err(error_from_swift(error));
387        }
388
389        if json_ptr.is_null() {
390            return Err(Error::InternalError(
391                "Quota usage returned null without an error".to_string(),
392            ));
393        }
394
395        let json = unsafe {
396            let json = CStr::from_ptr(json_ptr).to_string_lossy().into_owned();
397            ffi::fm_string_free(json_ptr);
398            json
399        };
400
401        quota_usage_from_json(&json)
402    }
403
404    /// Returns the Private Cloud Compute context window size in tokens.
405    ///
406    /// This performs a network request and can fail with
407    /// [`Error::NetworkFailure`] or [`Error::ServiceUnavailable`].
408    pub fn context_size(&self) -> Result<u64> {
409        LanguageModel::context_size(self)
410    }
411
412    pub(crate) fn as_ptr(&self) -> SwiftPtr {
413        self.handle.as_ptr()
414    }
415}
416
417#[cfg(feature = "private-cloud-compute")]
418impl private::Sealed for PrivateCloudComputeLanguageModel {}
419
420#[cfg(feature = "private-cloud-compute")]
421impl LanguageModel for PrivateCloudComputeLanguageModel {
422    fn raw_model_ptr(&self) -> *mut std::ffi::c_void {
423        self.as_ptr()
424    }
425}
426
427#[cfg(feature = "private-cloud-compute")]
428impl std::fmt::Debug for PrivateCloudComputeLanguageModel {
429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430        f.debug_struct("PrivateCloudComputeLanguageModel")
431            .field("availability", &self.availability())
432            .finish()
433    }
434}
435
436/// The user's daily Private Cloud Compute quota usage.
437///
438/// Returned by [`PrivateCloudComputeLanguageModel::quota_usage`]. Apple does
439/// not publish numeric limits; applications react to the reported status.
440#[cfg(feature = "private-cloud-compute")]
441#[derive(Debug, Clone, PartialEq)]
442pub struct QuotaUsage {
443    /// The user's position relative to their quota limit.
444    pub status: QuotaStatus,
445    /// When the quota next resets, if the system reports it.
446    pub reset_date: Option<SystemTime>,
447    /// Whether the system can show the user a quota-increase suggestion
448    /// (for example, upgrading to iCloud+).
449    pub has_limit_increase_suggestion: bool,
450}
451
452#[cfg(feature = "private-cloud-compute")]
453impl QuotaUsage {
454    /// Returns true when the quota is exhausted until the reset date.
455    pub fn is_limit_reached(&self) -> bool {
456        self.status == QuotaStatus::LimitReached
457    }
458}
459
460/// Position of the user's Private Cloud Compute usage relative to the quota.
461#[cfg(feature = "private-cloud-compute")]
462#[non_exhaustive]
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub enum QuotaStatus {
465    /// Requests are being served.
466    BelowLimit {
467        /// Whether usage is close enough to the limit that the application
468        /// should prepare an on-device fallback.
469        is_approaching_limit: bool,
470    },
471    /// The quota is exhausted; requests fail until the quota resets.
472    LimitReached,
473    /// A quota state this crate version does not recognize.
474    Unknown,
475}
476
477#[cfg(feature = "private-cloud-compute")]
478#[derive(serde::Deserialize)]
479#[serde(rename_all = "camelCase")]
480struct QuotaUsageDto {
481    status: String,
482    #[serde(default)]
483    is_approaching_limit: Option<bool>,
484    #[serde(default)]
485    reset_date: Option<f64>,
486    #[serde(default)]
487    has_limit_increase_suggestion: bool,
488}
489
490#[cfg(feature = "private-cloud-compute")]
491fn quota_usage_from_json(json: &str) -> Result<QuotaUsage> {
492    let dto: QuotaUsageDto = serde_json::from_str(json)
493        .map_err(|error| Error::InternalError(format!("Invalid quota usage JSON: {error}")))?;
494
495    let status = match dto.status.as_str() {
496        "belowLimit" => QuotaStatus::BelowLimit {
497            is_approaching_limit: dto.is_approaching_limit.unwrap_or(false),
498        },
499        "limitReached" => QuotaStatus::LimitReached,
500        _ => QuotaStatus::Unknown,
501    };
502
503    Ok(QuotaUsage {
504        status,
505        reset_date: dto.reset_date.and_then(unix_seconds_to_system_time),
506        has_limit_increase_suggestion: dto.has_limit_increase_suggestion,
507    })
508}
509
510#[cfg(feature = "private-cloud-compute")]
511fn unix_seconds_to_system_time(seconds: f64) -> Option<SystemTime> {
512    if seconds >= 0.0 {
513        UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(seconds).ok()?)
514    } else {
515        UNIX_EPOCH.checked_sub(Duration::try_from_secs_f64(-seconds).ok()?)
516    }
517}
518
519fn token_usage_from_raw(token_count: i64) -> Result<TokenUsage> {
520    if token_count < 0 {
521        return Err(Error::InternalError(
522            "Token usage API returned a negative token count".to_string(),
523        ));
524    }
525
526    let token_count = usize::try_from(token_count)
527        .map_err(|_| Error::InternalError("Token usage value does not fit in usize".to_string()))?;
528
529    Ok(TokenUsage {
530        token_count,
531        estimated: false,
532    })
533}
534
535/// Copies and frees a Swift-allocated (`strdup`) error string, or returns
536/// `None` for a null pointer.
537///
538/// # Safety
539///
540/// `ptr` must be null or a `strdup` allocation owned by the caller.
541unsafe fn take_error_string(ptr: *mut std::ffi::c_char) -> Option<String> {
542    if ptr.is_null() {
543        return None;
544    }
545    let value = unsafe { CStr::from_ptr(ptr) }
546        .to_string_lossy()
547        .into_owned();
548    unsafe { ffi::fm_string_free(ptr) };
549    Some(value)
550}
551
552/// Converts a Swift error pointer to a Rust Error.
553pub(crate) fn error_from_swift(error: SwiftPtr) -> Error {
554    if error.is_null() {
555        return Error::InternalError(
556            "FFI error object was null; unable to retrieve error details".to_string(),
557        );
558    }
559
560    let code = unsafe { ffi::fm_error_code(error) };
561
562    let message = unsafe { take_error_string(ffi::fm_error_message(error)) }
563        .unwrap_or_else(|| "Error message unavailable (null pointer from Swift)".to_string());
564
565    // Extract tool context if this is a tool error
566    let tool_name = unsafe { take_error_string(ffi::fm_error_tool_name(error)) };
567
568    let tool_arguments = unsafe { take_error_string(ffi::fm_error_tool_arguments(error)) }
569        .and_then(|json_str| serde_json::from_str(&json_str).ok());
570
571    unsafe {
572        ffi::fm_error_free(error);
573    }
574
575    if let ffi::ErrorCode::ToolError = ffi::ErrorCode::from(code) {
576        // Construct ToolCallError with context if available
577        return Error::ToolCall(ToolCallError {
578            tool_name: tool_name.unwrap_or_else(|| "unknown".to_string()),
579            arguments: tool_arguments.unwrap_or(serde_json::Value::Null),
580            inner_error: message,
581        });
582    }
583
584    error_from_parts(code, message)
585}
586
587/// Maps an FFI error code and message onto a typed [`Error`].
588///
589/// Shared by the blocking respond paths (via [`error_from_swift`]) and the
590/// streaming callbacks, which receive only a code and a message. Streaming
591/// tool errors keep the [`Error::ToolCall`] category; the tool name is only
592/// available embedded in the message, so the structured field is "unknown".
593pub(crate) fn error_from_parts(code: std::ffi::c_int, message: String) -> Error {
594    match ffi::ErrorCode::from(code) {
595        ffi::ErrorCode::ModelNotAvailable => Error::ModelNotAvailable,
596        ffi::ErrorCode::GenerationFailed => Error::GenerationError(message),
597        ffi::ErrorCode::Cancelled => Error::Cancelled(message),
598        ffi::ErrorCode::ToolError => Error::ToolCall(ToolCallError {
599            tool_name: "unknown".to_string(),
600            arguments: serde_json::Value::Null,
601            inner_error: message,
602        }),
603        ffi::ErrorCode::Timeout => Error::Timeout(message),
604        ffi::ErrorCode::UnsupportedPlatform => Error::UnsupportedPlatform(message),
605        ffi::ErrorCode::NetworkFailure => Error::NetworkFailure(message),
606        ffi::ErrorCode::QuotaLimitReached => Error::QuotaLimitReached(message),
607        ffi::ErrorCode::ServiceUnavailable => Error::ServiceUnavailable(message),
608        ffi::ErrorCode::ContextSizeExceeded => Error::ContextSizeExceeded(message),
609        ffi::ErrorCode::RateLimited => Error::RateLimited(message),
610        ffi::ErrorCode::GuardrailViolation => Error::GuardrailViolation(message),
611        ffi::ErrorCode::Refusal => Error::Refusal(message),
612        ffi::ErrorCode::UnsupportedCapability => Error::UnsupportedCapability(message),
613        ffi::ErrorCode::UnsupportedTranscriptContent => {
614            Error::UnsupportedTranscriptContent(message)
615        }
616        ffi::ErrorCode::UnsupportedGenerationGuide => Error::UnsupportedGenerationGuide(message),
617        ffi::ErrorCode::UnsupportedLanguageOrLocale => Error::UnsupportedLanguageOrLocale(message),
618        ffi::ErrorCode::AssetsUnavailable => Error::AssetsUnavailable(message),
619        ffi::ErrorCode::ConcurrentRequests => Error::ConcurrentRequests(message),
620        ffi::ErrorCode::InvalidInput => Error::InvalidInput(message),
621        ffi::ErrorCode::Unknown => Error::InternalError(message),
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    #[cfg(feature = "private-cloud-compute")]
628    use std::time::{Duration, UNIX_EPOCH};
629
630    use crate::error::Error;
631    use crate::ffi::{AvailabilityCode, ErrorCode};
632    use crate::model::{ModelAvailability, error_from_parts, token_usage_from_raw};
633    #[cfg(feature = "private-cloud-compute")]
634    use crate::model::{QuotaStatus, quota_usage_from_json, unix_seconds_to_system_time};
635
636    #[cfg(feature = "private-cloud-compute")]
637    #[test]
638    fn quota_usage_should_parse_below_limit() {
639        let usage = quota_usage_from_json(
640            r#"{"status":"belowLimit","isApproachingLimit":true,"resetDate":1786000000,"hasLimitIncreaseSuggestion":true}"#,
641        )
642        .expect("below-limit quota JSON should parse");
643
644        assert_eq!(
645            usage.status,
646            QuotaStatus::BelowLimit {
647                is_approaching_limit: true
648            }
649        );
650        assert!(!usage.is_limit_reached());
651        assert_eq!(
652            usage.reset_date,
653            Some(UNIX_EPOCH + Duration::from_secs(1_786_000_000))
654        );
655        assert!(usage.has_limit_increase_suggestion);
656    }
657
658    #[cfg(feature = "private-cloud-compute")]
659    #[test]
660    fn quota_usage_should_parse_limit_reached_without_optional_fields() {
661        let usage = quota_usage_from_json(r#"{"status":"limitReached"}"#)
662            .expect("limit-reached quota JSON should parse");
663
664        assert_eq!(usage.status, QuotaStatus::LimitReached);
665        assert!(usage.is_limit_reached());
666        assert_eq!(usage.reset_date, None);
667        assert!(!usage.has_limit_increase_suggestion);
668    }
669
670    #[cfg(feature = "private-cloud-compute")]
671    #[test]
672    fn quota_usage_should_map_future_statuses_to_unknown() {
673        let usage = quota_usage_from_json(r#"{"status":"throttled"}"#)
674            .expect("unrecognized quota status should parse");
675        assert_eq!(usage.status, QuotaStatus::Unknown);
676    }
677
678    #[cfg(feature = "private-cloud-compute")]
679    #[test]
680    fn quota_usage_should_reject_invalid_json() {
681        let err = quota_usage_from_json("not json").expect_err("invalid JSON should fail");
682        assert!(matches!(err, Error::InternalError(_)));
683    }
684
685    #[cfg(feature = "private-cloud-compute")]
686    #[test]
687    fn unix_seconds_should_reject_non_finite_values() {
688        assert_eq!(unix_seconds_to_system_time(f64::NAN), None);
689        assert_eq!(unix_seconds_to_system_time(f64::INFINITY), None);
690        assert!(unix_seconds_to_system_time(-1.0).is_some());
691    }
692
693    #[test]
694    fn token_usage_should_convert_positive_values() {
695        let usage = token_usage_from_raw(42).expect("positive token count should convert");
696        assert_eq!(usage.token_count, 42);
697        assert!(!usage.estimated);
698    }
699
700    #[test]
701    fn token_usage_should_reject_negative_values() {
702        let err = token_usage_from_raw(-1).expect_err("negative token count should fail");
703        assert!(err.to_string().contains("negative token count"));
704    }
705
706    #[test]
707    fn context_size_exceeded_ffi_code_preserves_original_detail() {
708        let detail = "Provided a request larger than the model context window.";
709        let error = error_from_parts(ErrorCode::ContextSizeExceeded as i32, detail.to_string());
710
711        match error {
712            Error::ContextSizeExceeded(message) => assert_eq!(message, detail),
713            other => panic!("expected ContextSizeExceeded, got {other:?}"),
714        }
715    }
716
717    #[test]
718    fn pcc_system_not_ready_should_remain_distinct() {
719        assert_eq!(
720            ModelAvailability::from(AvailabilityCode::PrivateCloudComputeSystemNotReady),
721            ModelAvailability::PrivateCloudComputeSystemNotReady
722        );
723    }
724}