Skip to main content

fm_rs/
session.rs

1//! Session management for `FoundationModels`.
2//!
3//! A session maintains conversation context between requests.
4
5use std::collections::{HashMap, HashSet};
6use std::ffi::{CStr, CString, c_char, c_int, c_void};
7use std::ptr::{self, NonNull};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11use crate::context::{ContextLimit, ContextUsage, context_usage_from_transcript};
12use crate::error::{Error, Result};
13use crate::ffi::{self, SwiftPtr};
14use crate::model::{LanguageModel, error_from_parts, error_from_swift};
15use crate::options::{GenerationOptions, ReasoningLevel};
16use crate::tool::{Tool, ToolResult, tools_to_json};
17
18/// Type alias for the tool map used in sessions.
19type ToolMapInner = HashMap<String, Arc<dyn Tool>>;
20
21/// Callback data shared between the session and tool callbacks.
22///
23/// Lifetime is reference-counted from both sides: the `Session` holds one
24/// strong reference and Swift's `ToolDispatcher` holds another. Any in-flight
25/// callback runs inside a dispatcher method, so ARC keeps this alive for the
26/// duration of every callback — no additional handshake is needed.
27struct ToolCallbackData {
28    tools: Mutex<ToolMapInner>,
29}
30
31/// Release the [`ToolCallbackData`] strong reference handed to Swift.
32///
33/// `Session::create_internal` gives Swift ownership of one `Arc` clone via
34/// `Arc::into_raw`, so something has to give it back. `ToolDispatcher.deinit`
35/// calls this when the dispatcher is deallocated.
36///
37/// # Safety
38///
39/// `user_data` must be null, or a pointer from `Arc::into_raw` on an
40/// `Arc<ToolCallbackData>` that has not already been reclaimed. Swift calls
41/// this exactly once per dispatcher, from `deinit`.
42#[unsafe(no_mangle)]
43pub unsafe extern "C" fn fm_rust_tool_data_free(user_data: *mut c_void) {
44    if user_data.is_null() {
45        return;
46    }
47    // Drops the dispatcher's strong reference — the only one on the success
48    // path — freeing the allocation and every `Arc<dyn Tool>` in its map.
49    // A user tool's Drop may panic; catch it rather than unwinding into
50    // Swift's deinit, which would abort the process.
51    let data = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
52    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(data)));
53}
54
55/// Response returned by the model.
56#[derive(Debug, Clone)]
57pub struct Response {
58    content: String,
59    usage: Option<SessionUsage>,
60}
61
62impl Response {
63    /// Creates a response, optionally carrying per-response token usage.
64    pub(crate) fn with_usage(content: String, usage: Option<SessionUsage>) -> Self {
65        Self { content, usage }
66    }
67
68    /// Returns exact token usage for this response (Foundation Models 27).
69    ///
70    /// `None` on pre-27 build SDKs or runtimes, or when the framework did
71    /// not report usage for this response.
72    pub fn usage(&self) -> Option<SessionUsage> {
73        self.usage
74    }
75
76    /// Gets the text content of the response.
77    pub fn content(&self) -> &str {
78        &self.content
79    }
80
81    /// Converts the response into its text content.
82    pub fn into_content(self) -> String {
83        self.content
84    }
85}
86
87impl AsRef<str> for Response {
88    fn as_ref(&self) -> &str {
89        &self.content
90    }
91}
92
93impl std::fmt::Display for Response {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.write_str(&self.content)
96    }
97}
98
99/// A session that interacts with a language model.
100///
101/// A session maintains state between requests, allowing for multi-turn conversations.
102/// You can reuse the same session for multiple prompts or create a new one each time.
103///
104/// Dropping a session requests cooperative cancellation. A Rust tool callback
105/// that is already queued or running may continue until it returns; its
106/// dispatcher-owned callback context remains valid for that duration.
107///
108/// # Example
109///
110/// ```rust,no_run
111/// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
112///
113/// let model = SystemLanguageModel::new()?;
114/// let session = Session::new(&model)?;
115///
116/// let response = session.respond("Hello!", &GenerationOptions::default())?;
117/// println!("{}", response.content());
118/// # Ok::<(), fm_rs::Error>(())
119/// ```
120pub struct Session {
121    ptr: NonNull<c_void>,
122}
123
124/// Apple's built-in system tools for sessions (Foundation Models 27).
125///
126/// These tools run inside the framework; unlike [`Tool`] implementations,
127/// they never call back into Rust. All use Apple's default configuration.
128///
129/// For reliable image-tool invocation, assign attachments a label with
130/// [`Attachment::with_label`] and reference that exact label in the prompt.
131/// Without an explicit label, the model may request an image label that does
132/// not exist and the tool call fails.
133///
134/// ```rust,no_run
135/// use fm_rs::{Attachment, GenerationOptions, Session, SystemLanguageModel, SystemTool};
136///
137/// let model = SystemLanguageModel::new()?;
138/// let session = Session::builder(&model)
139///     .system_tool(SystemTool::BarcodeReader)
140///     .build()?;
141///
142/// let response = session.respond_with_attachments(
143///     "Read the barcode in the attached image labeled \"qr\" and report its payload.",
144///     &[Attachment::file("qr.png").with_label("qr")],
145///     &GenerationOptions::default(),
146/// )?;
147/// println!("{}", response.content());
148/// # Ok::<(), fm_rs::Error>(())
149/// ```
150#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub enum SystemTool {
153    /// Vision text recognition over image attachments.
154    ///
155    /// Label attachments with [`Attachment::with_label`] and reference the
156    /// label in the prompt (see the enum-level example).
157    Ocr,
158    /// Vision barcode and QR-code reading over image attachments.
159    ///
160    /// Label attachments with [`Attachment::with_label`] and reference the
161    /// label in the prompt (see the enum-level example).
162    BarcodeReader,
163    /// Core Spotlight semantic search over the device index.
164    SpotlightSearch,
165}
166
167impl SystemTool {
168    fn ffi_name(self) -> &'static str {
169        match self {
170            SystemTool::Ocr => "ocr",
171            SystemTool::BarcodeReader => "barcodeReader",
172            SystemTool::SpotlightSearch => "spotlightSearch",
173        }
174    }
175}
176
177/// Builder combining instructions, custom tools, and built-in system tools.
178///
179/// ```rust,no_run
180/// use fm_rs::{Session, SystemLanguageModel, SystemTool};
181///
182/// let model = SystemLanguageModel::new()?;
183/// let session = Session::builder(&model)
184///     .instructions("Describe attached images and read any text in them.")
185///     .system_tool(SystemTool::Ocr)
186///     .build()?;
187/// # Ok::<(), fm_rs::Error>(())
188/// ```
189pub struct SessionBuilder<'m, M: LanguageModel + ?Sized> {
190    model: &'m M,
191    instructions: Option<String>,
192    tools: Vec<Arc<dyn Tool>>,
193    system_tools: Vec<SystemTool>,
194}
195
196impl<M: LanguageModel + ?Sized> SessionBuilder<'_, M> {
197    /// Sets the session instructions.
198    #[must_use]
199    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
200        self.instructions = Some(instructions.into());
201        self
202    }
203
204    /// Adds a Rust-implemented tool.
205    #[must_use]
206    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
207        self.tools.push(tool);
208        self
209    }
210
211    /// Adds a built-in system tool (Foundation Models 27).
212    ///
213    /// Session creation fails with [`crate::Error::UnsupportedPlatform`] on
214    /// pre-27 build SDKs or runtimes.
215    #[must_use]
216    pub fn system_tool(mut self, tool: SystemTool) -> Self {
217        self.system_tools.push(tool);
218        self
219    }
220
221    /// Builds the session.
222    pub fn build(self) -> Result<Session> {
223        Session::create_internal(
224            self.model,
225            self.instructions.as_deref(),
226            &self.tools,
227            &self.system_tools,
228        )
229    }
230}
231
232impl Session {
233    /// Creates a session builder for combining instructions, tools, and
234    /// built-in system tools.
235    pub fn builder<M: LanguageModel + ?Sized>(model: &M) -> SessionBuilder<'_, M> {
236        SessionBuilder {
237            model,
238            instructions: None,
239            tools: Vec::new(),
240            system_tools: Vec::new(),
241        }
242    }
243
244    /// Creates a new session with the given model.
245    pub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self> {
246        Self::create_internal(model, None, &[], &[])
247    }
248
249    /// Creates a new session with instructions.
250    ///
251    /// Instructions define the model's behavior and role.
252    pub fn with_instructions<M: LanguageModel + ?Sized>(
253        model: &M,
254        instructions: &str,
255    ) -> Result<Self> {
256        Self::create_internal(model, Some(instructions), &[], &[])
257    }
258
259    /// Creates a new session with tools.
260    ///
261    /// Tools allow the model to call external functions during generation.
262    pub fn with_tools<M: LanguageModel + ?Sized>(
263        model: &M,
264        tools: &[Arc<dyn Tool>],
265    ) -> Result<Self> {
266        Self::create_internal(model, None, tools, &[])
267    }
268
269    /// Creates a new session with both instructions and tools.
270    pub fn with_instructions_and_tools<M: LanguageModel + ?Sized>(
271        model: &M,
272        instructions: &str,
273        tools: &[Arc<dyn Tool>],
274    ) -> Result<Self> {
275        Self::create_internal(model, Some(instructions), tools, &[])
276    }
277
278    /// Creates a session from a transcript JSON string.
279    ///
280    /// This allows restoring a previous conversation.
281    /// Note: Restored sessions do not have tools - use `with_tools` for new sessions.
282    pub fn from_transcript<M: LanguageModel + ?Sized>(
283        model: &M,
284        transcript_json: &str,
285    ) -> Result<Self> {
286        let transcript_c = CString::new(transcript_json)?;
287        let mut error: SwiftPtr = ptr::null_mut();
288
289        let ptr = unsafe {
290            ffi::fm_session_from_transcript(
291                model.raw_model_ptr(),
292                transcript_c.as_ptr(),
293                &raw mut error,
294            )
295        };
296
297        if !error.is_null() {
298            return Err(error_from_swift(error));
299        }
300
301        NonNull::new(ptr).map(|ptr| Self { ptr }).ok_or_else(|| {
302            Error::InternalError(
303                "Session creation from transcript returned null without error. \
304                 The transcript JSON may be malformed or incompatible."
305                    .to_string(),
306            )
307        })
308    }
309
310    /// Internal helper to create a session.
311    fn create_internal<M: LanguageModel + ?Sized>(
312        model: &M,
313        instructions: Option<&str>,
314        tools: &[Arc<dyn Tool>],
315        system_tools: &[SystemTool],
316    ) -> Result<Self> {
317        let instructions_c = instructions.map(CString::new).transpose()?;
318        let instructions_ptr = instructions_c.as_ref().map_or(ptr::null(), |s| s.as_ptr());
319
320        // Serialize built-in system tool names for FFI
321        let system_tools_json = system_tools_json(system_tools)?;
322        let system_tools_ptr = system_tools_json
323            .as_ref()
324            .map_or(ptr::null(), |s| s.as_ptr());
325
326        // Build tool map and serialize for FFI
327        let mut tool_map = HashMap::new();
328        let tools_json = if tools.is_empty() {
329            None
330        } else {
331            let tool_refs: Vec<&dyn Tool> = tools.iter().map(std::convert::AsRef::as_ref).collect();
332            for tool in tools {
333                // Key by the trimmed name: tools_to_json advertises trimmed
334                // names, and Swift trims what the model produces before
335                // dispatching.
336                tool_map.insert(tool.name().trim().to_string(), Arc::clone(tool));
337            }
338            let json_str = tools_to_json(&tool_refs)?;
339            Some(CString::new(json_str)?)
340        };
341        let tools_ptr = tools_json.as_ref().map_or(ptr::null(), |s| s.as_ptr());
342
343        // Transfer one strong reference to Swift's ToolDispatcher, which
344        // reclaims it in deinit via fm_rust_tool_data_free.
345        let user_data = if tools.is_empty() {
346            ptr::null_mut()
347        } else {
348            Arc::into_raw(Arc::new(ToolCallbackData {
349                tools: Mutex::new(tool_map),
350            })) as *mut c_void
351        };
352
353        let mut error: SwiftPtr = ptr::null_mut();
354
355        let ptr = unsafe {
356            ffi::fm_session_create(
357                model.raw_model_ptr(),
358                instructions_ptr,
359                tools_ptr,
360                system_tools_ptr,
361                user_data,
362                session_tool_callback,
363                &raw mut error,
364            )
365        };
366
367        if !error.is_null() {
368            // Clean up leaked Arc if we allocated it
369            if !user_data.is_null() {
370                let _ = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
371            }
372            return Err(error_from_swift(error));
373        }
374
375        NonNull::new(ptr).map(|ptr| Self { ptr }).ok_or_else(|| {
376            // Clean up leaked Arc if we allocated it
377            if !user_data.is_null() {
378                let _ = unsafe { Arc::from_raw(user_data as *const ToolCallbackData) };
379            }
380            Error::InternalError(
381                "Session creation returned null without error. \
382                 Check model availability and instructions validity."
383                    .to_string(),
384            )
385        })
386    }
387
388    /// Sends a prompt and waits for the complete response.
389    ///
390    /// This method blocks until the model finishes generating.
391    pub fn respond(&self, prompt: &str, options: &GenerationOptions) -> Result<Response> {
392        let prompt_c = CString::new(prompt)?;
393        let options_json = options.to_json();
394        let options_c = CString::new(options_json)?;
395
396        let mut error: SwiftPtr = ptr::null_mut();
397
398        let response_ptr = unsafe {
399            ffi::fm_session_respond(
400                self.ptr.as_ptr(),
401                prompt_c.as_ptr(),
402                options_c.as_ptr(),
403                &raw mut error,
404            )
405        };
406
407        if !error.is_null() {
408            return Err(error_from_swift(error));
409        }
410
411        if response_ptr.is_null() {
412            return Err(Error::GenerationError("Received null response".to_string()));
413        }
414
415        let content = unsafe {
416            take_swift_string(response_ptr, |e| {
417                Error::GenerationError(format!("Invalid UTF-8 in response: {e}"))
418            })
419        }?;
420
421        Ok(Response::with_usage(
422            content,
423            self.fetch_last_response_usage(),
424        ))
425    }
426
427    /// Sends a prompt with Foundation Models 27 extended reasoning.
428    ///
429    /// Extended reasoning is a Foundation Models 27 `ContextOptions` request.
430    /// The framework decides whether the session's model honors the level;
431    /// models without the capability report a typed error. On an older build
432    /// SDK or runtime, this returns [`Error::UnsupportedPlatform`].
433    pub fn respond_with_reasoning(
434        &self,
435        prompt: &str,
436        options: &GenerationOptions,
437        reasoning_level: ReasoningLevel,
438    ) -> Result<Response> {
439        let prompt_c = CString::new(prompt)?;
440        let options_c = CString::new(options.to_json())?;
441        let mut error: SwiftPtr = ptr::null_mut();
442
443        let response_ptr = unsafe {
444            ffi::fm_session_respond_with_reasoning(
445                self.ptr.as_ptr(),
446                prompt_c.as_ptr(),
447                options_c.as_ptr(),
448                reasoning_level.as_ffi_code(),
449                &raw mut error,
450            )
451        };
452
453        if !error.is_null() {
454            return Err(error_from_swift(error));
455        }
456
457        if response_ptr.is_null() {
458            return Err(Error::GenerationError(
459                "Received null reasoning response".to_string(),
460            ));
461        }
462
463        let content = unsafe {
464            take_swift_string(response_ptr, |error| {
465                Error::GenerationError(format!("Invalid UTF-8 in reasoning response: {error}"))
466            })
467        }?;
468
469        Ok(Response::with_usage(
470            content,
471            self.fetch_last_response_usage(),
472        ))
473    }
474
475    /// Sends a prompt with extended reasoning and waits up to `timeout`.
476    ///
477    /// If `timeout` is zero, this behaves like
478    /// [`respond_with_reasoning`](Self::respond_with_reasoning).
479    /// Positive sub-millisecond timeouts are rounded up to one millisecond.
480    ///
481    /// Timeout cancellation is cooperative: the abandoned generation may keep
482    /// running in the background, in which case new requests report
483    /// [`Error::ConcurrentRequests`] until it finishes, and an
484    /// already-dispatched tool call may still run (side effects included)
485    /// after this method has returned [`Error::Timeout`].
486    pub fn respond_with_reasoning_timeout(
487        &self,
488        prompt: &str,
489        options: &GenerationOptions,
490        reasoning_level: ReasoningLevel,
491        timeout: Duration,
492    ) -> Result<Response> {
493        if timeout.is_zero() {
494            return self.respond_with_reasoning(prompt, options, reasoning_level);
495        }
496
497        let timeout_ms = timeout_millis(timeout)?;
498        let prompt_c = CString::new(prompt)?;
499        let options_c = CString::new(options.to_json())?;
500        let mut error: SwiftPtr = ptr::null_mut();
501
502        let response_ptr = unsafe {
503            ffi::fm_session_respond_with_reasoning_timeout(
504                self.ptr.as_ptr(),
505                prompt_c.as_ptr(),
506                options_c.as_ptr(),
507                reasoning_level.as_ffi_code(),
508                timeout_ms,
509                &raw mut error,
510            )
511        };
512
513        if !error.is_null() {
514            return Err(error_from_swift(error));
515        }
516
517        if response_ptr.is_null() {
518            return Err(Error::GenerationError(
519                "Received null reasoning response".to_string(),
520            ));
521        }
522
523        let content = unsafe {
524            take_swift_string(response_ptr, |error| {
525                Error::GenerationError(format!("Invalid UTF-8 in reasoning response: {error}"))
526            })
527        }?;
528
529        Ok(Response::with_usage(
530            content,
531            self.fetch_last_response_usage(),
532        ))
533    }
534
535    /// Sends a prompt and waits for the complete response, with a timeout.
536    ///
537    /// If `timeout` is zero, this behaves like [`respond`](Self::respond).
538    /// Positive sub-millisecond timeouts are rounded up to one millisecond.
539    ///
540    /// Timeout cancellation is cooperative: the abandoned generation may keep
541    /// running in the background, in which case new requests report
542    /// [`Error::ConcurrentRequests`] until it finishes, and an
543    /// already-dispatched tool call may still run (side effects included)
544    /// after this method has returned [`Error::Timeout`].
545    pub fn respond_with_timeout(
546        &self,
547        prompt: &str,
548        options: &GenerationOptions,
549        timeout: Duration,
550    ) -> Result<Response> {
551        if timeout.is_zero() {
552            return self.respond(prompt, options);
553        }
554
555        let timeout_ms = timeout_millis(timeout)?;
556
557        let prompt_c = CString::new(prompt)?;
558        let options_json = options.to_json();
559        let options_c = CString::new(options_json)?;
560
561        let mut error: SwiftPtr = ptr::null_mut();
562
563        let response_ptr = unsafe {
564            ffi::fm_session_respond_with_timeout(
565                self.ptr.as_ptr(),
566                prompt_c.as_ptr(),
567                options_c.as_ptr(),
568                timeout_ms,
569                &raw mut error,
570            )
571        };
572
573        if !error.is_null() {
574            return Err(error_from_swift(error));
575        }
576
577        if response_ptr.is_null() {
578            return Err(Error::GenerationError("Received null response".to_string()));
579        }
580
581        let content = unsafe {
582            take_swift_string(response_ptr, |e| {
583                Error::GenerationError(format!("Invalid UTF-8 in response: {e}"))
584            })
585        }?;
586
587        Ok(Response::with_usage(
588            content,
589            self.fetch_last_response_usage(),
590        ))
591    }
592
593    /// Sends a prompt and streams the response.
594    ///
595    /// The `on_chunk` callback is called for each text chunk as it arrives.
596    /// Chunks are incremental: concatenating every chunk yields the full
597    /// response. This method blocks until streaming is complete.
598    ///
599    /// # Example
600    ///
601    /// ```rust,no_run
602    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
603    ///
604    /// let model = SystemLanguageModel::new()?;
605    /// let session = Session::new(&model)?;
606    ///
607    /// session.stream_response("Tell me a story", &GenerationOptions::default(), |chunk| {
608    ///     print!("{}", chunk);
609    /// })?;
610    /// # Ok::<(), fm_rs::Error>(())
611    /// ```
612    pub fn stream_response<F>(
613        &self,
614        prompt: &str,
615        options: &GenerationOptions,
616        on_chunk: F,
617    ) -> Result<()>
618    where
619        F: FnMut(&str) + Send,
620    {
621        let prompt_c = CString::new(prompt)?;
622        let options_json = options.to_json();
623        let options_c = CString::new(options_json)?;
624
625        // Create callback state
626        let state = Box::new(StreamState {
627            session_ptr: self.ptr,
628            on_chunk: Mutex::new(Box::new(on_chunk)),
629            error: Mutex::new(None),
630        });
631        let state_ptr = Box::into_raw(state).cast::<c_void>();
632
633        unsafe {
634            ffi::fm_session_stream(
635                self.ptr.as_ptr(),
636                prompt_c.as_ptr(),
637                options_c.as_ptr(),
638                state_ptr,
639                stream_chunk_callback,
640                stream_done_callback,
641                stream_error_callback,
642            );
643        }
644
645        // Reclaim the state and check for errors
646        let state = unsafe { Box::from_raw(state_ptr.cast::<StreamState>()) };
647        let error = state.error.lock().map_err(|_| Error::PoisonError)?;
648        if let Some((code, message)) = error.as_ref() {
649            return Err(error_from_parts(*code, message.clone()));
650        }
651
652        Ok(())
653    }
654
655    /// Sends a prompt with image attachments and blocks until the response
656    /// is ready (Foundation Models 27 multimodal prompting).
657    ///
658    /// The on-device model accepts images for description, extraction, and
659    /// classification; the framework handles scaling and color conversion.
660    /// With no attachments this behaves like [`respond`](Self::respond).
661    /// Requires a 27 build SDK and runtime; otherwise returns
662    /// [`Error::UnsupportedPlatform`]. Models without the image capability
663    /// report [`Error::UnsupportedCapability`].
664    pub fn respond_with_attachments(
665        &self,
666        prompt: &str,
667        attachments: &[Attachment<'_>],
668        options: &GenerationOptions,
669    ) -> Result<Response> {
670        if attachments.is_empty() {
671            return self.respond(prompt, options);
672        }
673
674        let (specs_json, buffers, buffer_lens) = attachment_specs(attachments)?;
675        let buffer_count = c_int::try_from(buffers.len())
676            .map_err(|_| Error::InvalidInput("Too many attachments".to_string()))?;
677
678        let prompt_c = CString::new(prompt)?;
679        let options_c = CString::new(options.to_json())?;
680        let specs_c = CString::new(specs_json)?;
681        let mut error: SwiftPtr = ptr::null_mut();
682
683        let response_ptr = unsafe {
684            ffi::fm_session_respond_with_attachments(
685                self.ptr.as_ptr(),
686                prompt_c.as_ptr(),
687                options_c.as_ptr(),
688                specs_c.as_ptr(),
689                buffers.as_ptr(),
690                buffer_lens.as_ptr(),
691                buffer_count,
692                &raw mut error,
693            )
694        };
695
696        if !error.is_null() {
697            return Err(error_from_swift(error));
698        }
699
700        if response_ptr.is_null() {
701            return Err(Error::GenerationError(
702                "Received null multimodal response".to_string(),
703            ));
704        }
705
706        let content = unsafe {
707            take_swift_string(response_ptr, |error| {
708                Error::GenerationError(format!("Invalid UTF-8 in multimodal response: {error}"))
709            })
710        }?;
711
712        Ok(Response::with_usage(
713            content,
714            self.fetch_last_response_usage(),
715        ))
716    }
717
718    /// Returns exact cumulative token usage for this session.
719    ///
720    /// Foundation Models 27 reports authoritative input, cached-input,
721    /// output, and reasoning token counts across all requests in this
722    /// session. To measure a single request, snapshot before and after and
723    /// use [`SessionUsage::delta_since`]. Per-response usage is bridged into
724    /// [`Response::usage`] on blocking response paths; per-response usage for
725    /// streaming remains unsupported. On older build SDKs or runtimes this
726    /// returns [`Error::UnsupportedPlatform`]; use [`crate::estimate_tokens`]
727    /// there instead.
728    pub fn usage(&self) -> Result<SessionUsage> {
729        let mut error: SwiftPtr = ptr::null_mut();
730        let json_ptr = unsafe { ffi::fm_session_usage(self.ptr.as_ptr(), &raw mut error) };
731
732        if !error.is_null() {
733            return Err(error_from_swift(error));
734        }
735
736        if json_ptr.is_null() {
737            return Err(Error::InternalError(
738                "Session usage returned null without an error".to_string(),
739            ));
740        }
741
742        let json = unsafe {
743            let json = CStr::from_ptr(json_ptr).to_string_lossy().into_owned();
744            ffi::fm_string_free(json_ptr);
745            json
746        };
747
748        session_usage_from_json(&json)
749    }
750
751    /// Replaces this session's transcript (Foundation Models 27).
752    ///
753    /// The JSON must be a Foundation Models `Transcript`, such as one
754    /// returned by [`transcript_json`](Self::transcript_json) and edited. Fails while
755    /// the session is responding. On older build SDKs or runtimes this
756    /// returns [`Error::UnsupportedPlatform`]; there, create a new session
757    /// with [`Session::from_transcript`] instead.
758    pub fn set_transcript(&self, transcript_json: &str) -> Result<()> {
759        let transcript_c = CString::new(transcript_json)?;
760        let mut error: SwiftPtr = ptr::null_mut();
761
762        let replaced = unsafe {
763            ffi::fm_session_set_transcript(self.ptr.as_ptr(), transcript_c.as_ptr(), &raw mut error)
764        };
765
766        if !error.is_null() {
767            return Err(error_from_swift(error));
768        }
769
770        if replaced {
771            Ok(())
772        } else {
773            Err(Error::InternalError(
774                "Transcript replacement failed without an error".to_string(),
775            ))
776        }
777    }
778
779    /// Sets or clears how the transcript is repaired after a failed request
780    /// (Foundation Models 27).
781    ///
782    /// `None` restores the framework default. On older build SDKs or
783    /// runtimes this returns [`Error::UnsupportedPlatform`].
784    pub fn set_transcript_error_handling_policy(
785        &self,
786        policy: Option<TranscriptErrorHandlingPolicy>,
787    ) -> Result<()> {
788        let code = match policy {
789            None => 0,
790            Some(TranscriptErrorHandlingPolicy::RevertTranscript) => 1,
791            Some(TranscriptErrorHandlingPolicy::PreserveTranscript) => 2,
792        };
793        let mut error: SwiftPtr = ptr::null_mut();
794
795        let applied = unsafe {
796            ffi::fm_session_set_transcript_error_policy(self.ptr.as_ptr(), code, &raw mut error)
797        };
798
799        if !error.is_null() {
800            return Err(error_from_swift(error));
801        }
802
803        if applied {
804            Ok(())
805        } else {
806            Err(Error::InternalError(
807                "Transcript policy update failed without an error".to_string(),
808            ))
809        }
810    }
811
812    /// Fetches the usage recorded for the most recent completed response.
813    ///
814    /// Returns `None` on pre-27 build SDKs or runtimes, or when no blocking
815    /// response has completed yet. Unreadable payloads also map to `None`;
816    /// [`Response::usage`] documents this as "not reported".
817    fn fetch_last_response_usage(&self) -> Option<SessionUsage> {
818        let json_ptr = unsafe { ffi::fm_session_last_response_usage(self.ptr.as_ptr()) };
819        if json_ptr.is_null() {
820            return None;
821        }
822
823        let json = unsafe {
824            let json = CStr::from_ptr(json_ptr).to_string_lossy().into_owned();
825            ffi::fm_string_free(json_ptr);
826            json
827        };
828
829        session_usage_from_json(&json).ok()
830    }
831
832    /// Cancels the in-flight generation (blocking or streaming), if any.
833    ///
834    /// Every generation method blocks the calling thread and `Session` is not
835    /// `Sync`, so this cannot be reached while a request is in flight. To
836    /// cancel from another thread, obtain a [`CancellationHandle`] via
837    /// [`cancellation_handle`](Self::cancellation_handle) before starting.
838    pub fn cancel(&self) {
839        unsafe {
840            ffi::fm_session_cancel(self.ptr.as_ptr());
841        }
842    }
843
844    /// Returns a thread-safe handle that can cancel this session's in-flight
845    /// generation from another thread.
846    ///
847    /// The handle holds its own reference to the underlying Swift session, so
848    /// it remains safe to use (as a no-op) after the `Session` is dropped.
849    /// It is session-scoped rather than generation-scoped: [`cancel`](CancellationHandle::cancel)
850    /// targets whichever generation is in flight when it is called. A delayed
851    /// call intended for an earlier generation can therefore cancel a later
852    /// one; coordinate its lifetime with the operation it is meant to cancel.
853    ///
854    /// # Example
855    ///
856    /// ```rust,no_run
857    /// use fm_rs::{GenerationOptions, Session, SystemLanguageModel};
858    ///
859    /// let model = SystemLanguageModel::new()?;
860    /// let session = Session::new(&model)?;
861    /// let handle = session.cancellation_handle();
862    ///
863    /// let canceller = std::thread::spawn(move || {
864    ///     std::thread::sleep(std::time::Duration::from_millis(100));
865    ///     handle.cancel();
866    /// });
867    ///
868    /// let result = session.stream_response(
869    ///     "Tell me a very long story",
870    ///     &GenerationOptions::default(),
871    ///     |chunk| print!("{chunk}"),
872    /// );
873    /// assert!(matches!(result, Err(fm_rs::Error::Cancelled(_))));
874    /// canceller.join().expect("canceller thread panicked");
875    /// # Ok::<(), fm_rs::Error>(())
876    /// ```
877    pub fn cancellation_handle(&self) -> CancellationHandle {
878        unsafe { ffi::fm_session_retain(self.ptr.as_ptr()) };
879        CancellationHandle { ptr: self.ptr }
880    }
881
882    /// Checks if the session is currently generating a response.
883    pub fn is_responding(&self) -> bool {
884        unsafe { ffi::fm_session_is_responding(self.ptr.as_ptr()) }
885    }
886
887    /// Gets the session transcript as a JSON string.
888    ///
889    /// This can be used to persist and restore conversations.
890    pub fn transcript_json(&self) -> Result<String> {
891        let mut error: SwiftPtr = ptr::null_mut();
892        let ptr = unsafe { ffi::fm_session_get_transcript(self.ptr.as_ptr(), &raw mut error) };
893
894        if !error.is_null() {
895            return Err(error_from_swift(error));
896        }
897
898        if ptr.is_null() {
899            return Err(Error::InternalError(
900                "Transcript retrieval returned null without error. \
901                 The session may be in an invalid state."
902                    .to_string(),
903            ));
904        }
905
906        unsafe {
907            take_swift_string(ptr, |e| {
908                Error::InternalError(format!("Invalid UTF-8 in transcript: {e}"))
909            })
910        }
911    }
912
913    /// Estimates current context usage based on the session transcript.
914    pub fn context_usage(&self, limit: &ContextLimit) -> Result<ContextUsage> {
915        let transcript_json = self.transcript_json()?;
916        context_usage_from_transcript(&transcript_json, limit)
917    }
918
919    /// Returns an error if the estimated context usage exceeds the configured limit.
920    pub fn ensure_context_within(&self, limit: &ContextLimit) -> Result<()> {
921        let usage = self.context_usage(limit)?;
922        if usage.over_limit {
923            return Err(Error::InvalidInput(format!(
924                "Estimated context usage {} exceeds configured limit {} (reserved: {})",
925                usage.estimated_tokens, usage.max_tokens, usage.reserved_response_tokens
926            )));
927        }
928        Ok(())
929    }
930
931    /// Prewarms the model with an optional prompt prefix.
932    ///
933    /// This can reduce latency for the first response.
934    pub fn prewarm(&self, prompt_prefix: Option<&str>) -> Result<()> {
935        let prefix_c = prompt_prefix.map(CString::new).transpose()?;
936        let prefix_ptr = prefix_c.as_ref().map_or(ptr::null(), |s| s.as_ptr());
937
938        unsafe {
939            ffi::fm_session_prewarm(self.ptr.as_ptr(), prefix_ptr);
940        }
941
942        Ok(())
943    }
944
945    /// Sends a prompt and returns a structured JSON response.
946    ///
947    /// The schema is a JSON Schema that describes the expected output format.
948    /// The model is instructed to produce JSON that matches the schema.
949    ///
950    /// # Example
951    ///
952    /// ```rust,no_run
953    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
954    /// use serde::Deserialize;
955    /// use serde_json::json;
956    ///
957    /// #[derive(Deserialize)]
958    /// struct Person {
959    ///     name: String,
960    ///     age: u32,
961    /// }
962    ///
963    /// let model = SystemLanguageModel::new()?;
964    /// let session = Session::new(&model)?;
965    ///
966    /// let schema = json!({
967    ///     "type": "object",
968    ///     "properties": {
969    ///         "name": { "type": "string" },
970    ///         "age": { "type": "integer" }
971    ///     },
972    ///     "required": ["name", "age"]
973    /// });
974    ///
975    /// let json_str = session.respond_json(
976    ///     "Generate a fictional person",
977    ///     &schema,
978    ///     &GenerationOptions::default()
979    /// )?;
980    ///
981    /// let person: Person = serde_json::from_str(&json_str)?;
982    /// # Ok::<(), Box<dyn std::error::Error>>(())
983    /// ```
984    pub fn respond_json(
985        &self,
986        prompt: &str,
987        schema: &serde_json::Value,
988        options: &GenerationOptions,
989    ) -> Result<String> {
990        let prompt_c = CString::new(prompt)?;
991        let schema_json = serde_json::to_string(schema)?;
992        let schema_c = CString::new(schema_json)?;
993        let options_json = options.to_json();
994        let options_c = CString::new(options_json)?;
995
996        let mut error: SwiftPtr = ptr::null_mut();
997
998        let response_ptr = unsafe {
999            ffi::fm_session_respond_json(
1000                self.ptr.as_ptr(),
1001                prompt_c.as_ptr(),
1002                schema_c.as_ptr(),
1003                options_c.as_ptr(),
1004                &raw mut error,
1005            )
1006        };
1007
1008        if !error.is_null() {
1009            return Err(error_from_swift(error));
1010        }
1011
1012        if response_ptr.is_null() {
1013            return Err(Error::GenerationError(
1014                "Received null response from JSON generation".to_string(),
1015            ));
1016        }
1017
1018        let content = unsafe {
1019            take_swift_string(response_ptr, |e| {
1020                Error::GenerationError(format!("Invalid UTF-8 in JSON response: {e}"))
1021            })
1022        }?;
1023
1024        Ok(content)
1025    }
1026
1027    /// Sends a prompt and returns a structured JSON response with a timeout.
1028    ///
1029    /// The response content contains the extracted JSON string. On Foundation Models 27,
1030    /// [`Response::usage`] also exposes the framework's per-response token usage when
1031    /// available. If `timeout` is zero, this uses the same path as
1032    /// [`respond_json`](Self::respond_json). Positive sub-millisecond timeouts are rounded up
1033    /// to one millisecond, the finest resolution supported by the Swift bridge.
1034    ///
1035    /// The timeout bounds only the caller's wait. On expiry, the bridge requests cooperative
1036    /// task cancellation and returns [`Error::Timeout`]; it cannot force Foundation Models
1037    /// framework work to stop immediately. While the abandoned generation drains, new
1038    /// requests report [`Error::ConcurrentRequests`], and an already-dispatched tool call
1039    /// may still run (side effects included) after this method has returned.
1040    ///
1041    /// # Example
1042    ///
1043    /// ```rust,no_run
1044    /// use std::time::Duration;
1045    ///
1046    /// use fm_rs::{GenerationOptions, Session, SystemLanguageModel};
1047    /// use serde_json::json;
1048    ///
1049    /// let model = SystemLanguageModel::new()?;
1050    /// let session = Session::new(&model)?;
1051    /// let schema = json!({
1052    ///     "type": "object",
1053    ///     "properties": { "answer": { "type": "string" } },
1054    ///     "required": ["answer"]
1055    /// });
1056    ///
1057    /// let response = session.respond_json_with_timeout(
1058    ///     "Answer briefly",
1059    ///     &schema,
1060    ///     &GenerationOptions::default(),
1061    ///     Duration::from_secs(30),
1062    /// )?;
1063    /// let json: serde_json::Value = serde_json::from_str(response.content())?;
1064    /// # Ok::<(), Box<dyn std::error::Error>>(())
1065    /// ```
1066    pub fn respond_json_with_timeout(
1067        &self,
1068        prompt: &str,
1069        schema: &serde_json::Value,
1070        options: &GenerationOptions,
1071        timeout: Duration,
1072    ) -> Result<Response> {
1073        let Some(timeout_ms) = json_timeout_millis(timeout)? else {
1074            let content = self.respond_json(prompt, schema, options)?;
1075            return Ok(Response::with_usage(
1076                content,
1077                self.fetch_last_response_usage(),
1078            ));
1079        };
1080
1081        let prompt_c = CString::new(prompt)?;
1082        let schema_c = CString::new(serde_json::to_string(schema)?)?;
1083        let options_c = CString::new(options.to_json())?;
1084        let mut error: SwiftPtr = ptr::null_mut();
1085
1086        let response_ptr = unsafe {
1087            ffi::fm_session_respond_json_with_timeout(
1088                self.ptr.as_ptr(),
1089                prompt_c.as_ptr(),
1090                schema_c.as_ptr(),
1091                options_c.as_ptr(),
1092                timeout_ms,
1093                &raw mut error,
1094            )
1095        };
1096
1097        if !error.is_null() {
1098            return Err(error_from_swift(error));
1099        }
1100
1101        if response_ptr.is_null() {
1102            return Err(Error::GenerationError(
1103                "Received null response from JSON generation".to_string(),
1104            ));
1105        }
1106
1107        let content = unsafe {
1108            take_swift_string(response_ptr, |error| {
1109                Error::GenerationError(format!("Invalid UTF-8 in JSON response: {error}"))
1110            })
1111        }?;
1112
1113        Ok(Response::with_usage(
1114            content,
1115            self.fetch_last_response_usage(),
1116        ))
1117    }
1118
1119    /// Sends a prompt and returns a deserialized structured response.
1120    ///
1121    /// This is a convenience method that calls `respond_json` and deserializes
1122    /// the result into the specified type.
1123    ///
1124    /// # Example
1125    ///
1126    /// ```rust,no_run
1127    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
1128    /// use serde::Deserialize;
1129    /// use serde_json::json;
1130    ///
1131    /// #[derive(Deserialize)]
1132    /// struct Person {
1133    ///     name: String,
1134    ///     age: u32,
1135    /// }
1136    ///
1137    /// let model = SystemLanguageModel::new()?;
1138    /// let session = Session::new(&model)?;
1139    ///
1140    /// let schema = json!({
1141    ///     "type": "object",
1142    ///     "properties": {
1143    ///         "name": { "type": "string" },
1144    ///         "age": { "type": "integer" }
1145    ///     },
1146    ///     "required": ["name", "age"]
1147    /// });
1148    ///
1149    /// let person: Person = session.respond_structured(
1150    ///     "Generate a fictional person",
1151    ///     &schema,
1152    ///     &GenerationOptions::default()
1153    /// )?;
1154    /// # Ok::<(), Box<dyn std::error::Error>>(())
1155    /// ```
1156    pub fn respond_structured<T: serde::de::DeserializeOwned>(
1157        &self,
1158        prompt: &str,
1159        schema: &serde_json::Value,
1160        options: &GenerationOptions,
1161    ) -> Result<T> {
1162        let json_str = self.respond_json(prompt, schema, options)?;
1163        serde_json::from_str(&json_str)
1164            .map_err(|e| Error::InvalidInput(format!("Failed to deserialize response: {e}")))
1165    }
1166
1167    /// Sends a prompt and returns a deserialized structured response using a derived schema.
1168    ///
1169    /// This uses the [`crate::Generable`] implementation to obtain the JSON schema.
1170    pub fn respond_structured_gen<T>(&self, prompt: &str, options: &GenerationOptions) -> Result<T>
1171    where
1172        T: crate::Generable + serde::de::DeserializeOwned,
1173    {
1174        self.respond_structured(prompt, &T::schema(), options)
1175    }
1176
1177    /// Streams a structured JSON response.
1178    ///
1179    /// Unlike [`stream_response`](Self::stream_response), `on_chunk` receives
1180    /// the *cumulative* partial JSON generated so far on each call, not an
1181    /// incremental delta — render each snapshot in place rather than
1182    /// concatenating them. Partial snapshots may not be valid JSON until
1183    /// streaming completes.
1184    ///
1185    /// # Example
1186    ///
1187    /// ```rust,no_run
1188    /// use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
1189    /// use serde_json::json;
1190    ///
1191    /// let model = SystemLanguageModel::new()?;
1192    /// let session = Session::new(&model)?;
1193    ///
1194    /// let schema = json!({
1195    ///     "type": "object",
1196    ///     "properties": {
1197    ///         "items": { "type": "array", "items": { "type": "string" } }
1198    ///     }
1199    /// });
1200    ///
1201    /// session.stream_json(
1202    ///     "List 5 programming languages",
1203    ///     &schema,
1204    ///     &GenerationOptions::default(),
1205    ///     |chunk| {
1206    ///         print!("{chunk}");
1207    ///     }
1208    /// )?;
1209    /// # Ok::<(), fm_rs::Error>(())
1210    /// ```
1211    pub fn stream_json<F>(
1212        &self,
1213        prompt: &str,
1214        schema: &serde_json::Value,
1215        options: &GenerationOptions,
1216        on_chunk: F,
1217    ) -> Result<()>
1218    where
1219        F: FnMut(&str) + Send,
1220    {
1221        let prompt_c = CString::new(prompt)?;
1222        let schema_json = serde_json::to_string(schema)?;
1223        let schema_c = CString::new(schema_json)?;
1224        let options_json = options.to_json();
1225        let options_c = CString::new(options_json)?;
1226
1227        // Create callback state
1228        let state = Box::new(StreamState {
1229            session_ptr: self.ptr,
1230            on_chunk: Mutex::new(Box::new(on_chunk)),
1231            error: Mutex::new(None),
1232        });
1233        let state_ptr = Box::into_raw(state).cast::<c_void>();
1234
1235        unsafe {
1236            ffi::fm_session_stream_json(
1237                self.ptr.as_ptr(),
1238                prompt_c.as_ptr(),
1239                schema_c.as_ptr(),
1240                options_c.as_ptr(),
1241                state_ptr,
1242                stream_chunk_callback,
1243                stream_done_callback,
1244                stream_error_callback,
1245            );
1246        }
1247
1248        // Reclaim the state and check for errors
1249        let state = unsafe { Box::from_raw(state_ptr.cast::<StreamState>()) };
1250        let error = state.error.lock().map_err(|_| Error::PoisonError)?;
1251        if let Some((code, message)) = error.as_ref() {
1252            return Err(error_from_parts(*code, message.clone()));
1253        }
1254
1255        Ok(())
1256    }
1257}
1258
1259impl Drop for Session {
1260    fn drop(&mut self) {
1261        unsafe {
1262            ffi::fm_session_free(self.ptr.as_ptr());
1263        }
1264
1265        // Swift's ToolDispatcher owns the ToolCallbackData reference (via
1266        // Arc::into_raw) and reclaims it in deinit; any in-flight tool
1267        // callback runs inside a dispatcher method, so the data outlives
1268        // every callback.
1269    }
1270}
1271
1272// SAFETY: Session is a wrapper around a Swift object that uses
1273// DispatchQueue for thread safety internally.
1274unsafe impl Send for Session {}
1275
1276// Note: Session is NOT Sync because streaming callbacks use internal mutable state.
1277// To cancel or observe an in-flight generation from another thread, use
1278// Session::cancellation_handle().
1279
1280/// Thread-safe handle for cancelling a [`Session`]'s in-flight generation.
1281///
1282/// Created via [`Session::cancellation_handle`]. Holds its own reference to
1283/// the Swift session, so it may outlive the `Session`; cancelling after the
1284/// session is gone is a no-op. The handle is session-scoped, so a delayed
1285/// cancellation targets whichever generation is active at call time, not
1286/// necessarily the generation that was active when the handle was created.
1287pub struct CancellationHandle {
1288    ptr: NonNull<c_void>,
1289}
1290
1291impl CancellationHandle {
1292    /// Cancels the session's in-flight generation, if any.
1293    ///
1294    /// Covers blocking (`respond*`) and streaming calls alike; a cancelled
1295    /// call returns [`Error::Cancelled`]. Cancellation is cooperative, so the
1296    /// framework may finish a small amount of work before observing it. This
1297    /// targets the current generation at call time; discard or otherwise
1298    /// coordinate stale handles before starting a later generation.
1299    pub fn cancel(&self) {
1300        unsafe { ffi::fm_session_cancel(self.ptr.as_ptr()) };
1301    }
1302
1303    /// Returns whether the session is currently generating a response.
1304    pub fn is_responding(&self) -> bool {
1305        unsafe { ffi::fm_session_is_responding(self.ptr.as_ptr()) }
1306    }
1307}
1308
1309impl Drop for CancellationHandle {
1310    fn drop(&mut self) {
1311        unsafe { ffi::fm_session_release(self.ptr.as_ptr()) };
1312    }
1313}
1314
1315// SAFETY: the handle only calls into Swift entry points that guard their
1316// state with a lock (cancelCurrentTask) or read a framework-owned property
1317// (isResponding); the retained reference keeps the pointee alive.
1318unsafe impl Send for CancellationHandle {}
1319unsafe impl Sync for CancellationHandle {}
1320
1321/// Type alias for the chunk callback function.
1322type ChunkCallbackFn<'a> = dyn FnMut(&str) + Send + 'a;
1323
1324/// An image input for Foundation Models 27 multimodal prompting.
1325///
1326/// Create one from a file path or from encoded image bytes (PNG, JPEG,
1327/// HEIC, ...), then pass it to [`Session::respond_with_attachments`]. Label
1328/// attachments so prompts can reference specific images by name.
1329#[derive(Debug, Clone)]
1330pub struct Attachment<'a> {
1331    source: AttachmentSource<'a>,
1332    label: Option<String>,
1333}
1334
1335#[derive(Debug, Clone)]
1336enum AttachmentSource<'a> {
1337    File(std::path::PathBuf),
1338    ImageBytes(&'a [u8]),
1339}
1340
1341fn system_tools_json(system_tools: &[SystemTool]) -> Result<Option<CString>> {
1342    if system_tools.is_empty() {
1343        return Ok(None);
1344    }
1345
1346    let mut seen = HashSet::with_capacity(system_tools.len());
1347    let mut names = Vec::with_capacity(system_tools.len());
1348    for tool in system_tools {
1349        if !seen.insert(*tool) {
1350            return Err(Error::InvalidInput(format!(
1351                "Duplicate built-in system tool: {}",
1352                tool.ffi_name()
1353            )));
1354        }
1355        names.push(tool.ffi_name());
1356    }
1357
1358    Ok(Some(CString::new(serde_json::to_string(&names)?)?))
1359}
1360
1361impl<'a> Attachment<'a> {
1362    /// Creates an image attachment from a file on disk.
1363    pub fn file(path: impl Into<std::path::PathBuf>) -> Attachment<'static> {
1364        Attachment {
1365            source: AttachmentSource::File(path.into()),
1366            label: None,
1367        }
1368    }
1369
1370    /// Creates an image attachment from encoded image bytes.
1371    pub fn image_bytes(bytes: &'a [u8]) -> Attachment<'a> {
1372        Attachment {
1373            source: AttachmentSource::ImageBytes(bytes),
1374            label: None,
1375        }
1376    }
1377
1378    /// Labels the attachment so prompts can reference it by name.
1379    #[must_use]
1380    pub fn with_label(mut self, label: impl Into<String>) -> Self {
1381        self.label = Some(label.into());
1382        self
1383    }
1384}
1385
1386#[derive(serde::Serialize)]
1387#[serde(rename_all = "camelCase")]
1388struct AttachmentSpec<'a> {
1389    kind: &'static str,
1390    #[serde(skip_serializing_if = "Option::is_none")]
1391    path: Option<&'a str>,
1392    #[serde(skip_serializing_if = "Option::is_none")]
1393    buffer_index: Option<usize>,
1394    #[serde(skip_serializing_if = "Option::is_none")]
1395    label: Option<&'a str>,
1396}
1397
1398type AttachmentBuffers = (String, Vec<*const u8>, Vec<usize>);
1399
1400/// Serializes attachments to a JSON spec plus parallel byte-buffer arrays.
1401fn attachment_specs(attachments: &[Attachment<'_>]) -> Result<AttachmentBuffers> {
1402    let mut specs = Vec::with_capacity(attachments.len());
1403    let mut buffers = Vec::new();
1404    let mut buffer_lens = Vec::new();
1405
1406    for attachment in attachments {
1407        let label = attachment.label.as_deref();
1408        match &attachment.source {
1409            AttachmentSource::File(path) => {
1410                let path = path.to_str().ok_or_else(|| {
1411                    Error::InvalidInput(format!(
1412                        "Attachment path is not valid UTF-8: {}",
1413                        path.display()
1414                    ))
1415                })?;
1416                specs.push(AttachmentSpec {
1417                    kind: "file",
1418                    path: Some(path),
1419                    buffer_index: None,
1420                    label,
1421                });
1422            }
1423            AttachmentSource::ImageBytes(bytes) => {
1424                specs.push(AttachmentSpec {
1425                    kind: "data",
1426                    path: None,
1427                    buffer_index: Some(buffers.len()),
1428                    label,
1429                });
1430                buffers.push(bytes.as_ptr());
1431                buffer_lens.push(bytes.len());
1432            }
1433        }
1434    }
1435
1436    let json = serde_json::to_string(&specs)?;
1437    Ok((json, buffers, buffer_lens))
1438}
1439
1440/// Exact cumulative token usage reported by a Foundation Models 27 session.
1441///
1442/// Returned by [`Session::usage`]. Unlike [`crate::estimate_tokens`], these
1443/// counts are authoritative and include prompt caching and
1444/// extended-reasoning accounting.
1445#[non_exhaustive]
1446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1447pub struct SessionUsage {
1448    /// Total input tokens across all requests in this session.
1449    pub input_tokens: u64,
1450    /// Input tokens that were served from the prompt cache.
1451    pub cached_input_tokens: u64,
1452    /// Total output tokens across all responses in this session.
1453    pub output_tokens: u64,
1454    /// Output tokens spent on extended reasoning.
1455    pub reasoning_tokens: u64,
1456}
1457
1458impl SessionUsage {
1459    /// Returns the usage consumed since an earlier snapshot of this session.
1460    ///
1461    /// # Errors
1462    ///
1463    /// Returns [`Error::InvalidInput`] if any counter went backwards, which
1464    /// indicates the snapshots came from different sessions or were taken
1465    /// out of order.
1466    pub fn delta_since(&self, earlier: &SessionUsage) -> Result<SessionUsage> {
1467        let sub = |now: u64, before: u64, field: &str| {
1468            now.checked_sub(before).ok_or_else(|| {
1469                Error::InvalidInput(format!(
1470                    "Usage {field} went backwards ({now} < {before}); snapshots must come \
1471                     from the same session in order"
1472                ))
1473            })
1474        };
1475
1476        Ok(SessionUsage {
1477            input_tokens: sub(self.input_tokens, earlier.input_tokens, "input_tokens")?,
1478            cached_input_tokens: sub(
1479                self.cached_input_tokens,
1480                earlier.cached_input_tokens,
1481                "cached_input_tokens",
1482            )?,
1483            output_tokens: sub(self.output_tokens, earlier.output_tokens, "output_tokens")?,
1484            reasoning_tokens: sub(
1485                self.reasoning_tokens,
1486                earlier.reasoning_tokens,
1487                "reasoning_tokens",
1488            )?,
1489        })
1490    }
1491}
1492
1493#[derive(serde::Deserialize)]
1494#[serde(rename_all = "camelCase")]
1495#[expect(
1496    clippy::struct_field_names,
1497    reason = "the _tokens suffix maps to the FFI JSON keys and mirrors Apple's usage terminology"
1498)]
1499struct SessionUsageDto {
1500    input_tokens: i64,
1501    cached_input_tokens: i64,
1502    output_tokens: i64,
1503    reasoning_tokens: i64,
1504}
1505
1506fn session_usage_from_json(json: &str) -> Result<SessionUsage> {
1507    let dto: SessionUsageDto = serde_json::from_str(json)
1508        .map_err(|error| Error::InternalError(format!("Invalid session usage JSON: {error}")))?;
1509
1510    let count = |value: i64, field: &str| {
1511        u64::try_from(value).map_err(|_| {
1512            Error::InternalError(format!("Session usage {field} was negative: {value}"))
1513        })
1514    };
1515
1516    Ok(SessionUsage {
1517        input_tokens: count(dto.input_tokens, "inputTokens")?,
1518        cached_input_tokens: count(dto.cached_input_tokens, "cachedInputTokens")?,
1519        output_tokens: count(dto.output_tokens, "outputTokens")?,
1520        reasoning_tokens: count(dto.reasoning_tokens, "reasoningTokens")?,
1521    })
1522}
1523
1524/// How a session repairs its transcript after a failed request
1525/// (Foundation Models 27).
1526#[non_exhaustive]
1527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1528pub enum TranscriptErrorHandlingPolicy {
1529    /// Remove the failed request from the transcript.
1530    RevertTranscript,
1531    /// Keep the failed request in the transcript.
1532    PreserveTranscript,
1533}
1534
1535/// Internal state for streaming callbacks.
1536struct StreamState<'a> {
1537    session_ptr: NonNull<c_void>,
1538    on_chunk: Mutex<Box<ChunkCallbackFn<'a>>>,
1539    error: Mutex<Option<(c_int, String)>>,
1540}
1541
1542/// Callback invoked when a chunk arrives during streaming.
1543extern "C" fn stream_chunk_callback(user_data: *mut c_void, chunk: *const c_char) {
1544    if user_data.is_null() || chunk.is_null() {
1545        return;
1546    }
1547
1548    let state = unsafe { &*(user_data as *const StreamState) };
1549    let chunk_str = unsafe { CStr::from_ptr(chunk).to_string_lossy() };
1550
1551    // A panic here would unwind into Swift and abort the process; convert it
1552    // into a stream error instead. The poisoned mutex suppresses the user
1553    // callback for any chunks that arrive after the panic.
1554    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1555        if let Ok(mut on_chunk) = state.on_chunk.lock() {
1556            on_chunk(&chunk_str);
1557        }
1558    }))
1559    .is_err();
1560
1561    if panicked && let Ok(mut error) = state.error.lock() {
1562        error.get_or_insert((
1563            ffi::ErrorCode::Unknown as c_int,
1564            "Stream chunk callback panicked".to_string(),
1565        ));
1566    }
1567    if panicked {
1568        // Stop generation promptly; the error callback below preserves the
1569        // more specific callback-panic error already recorded above.
1570        unsafe { ffi::fm_session_cancel(state.session_ptr.as_ptr()) };
1571    }
1572}
1573
1574/// Callback invoked when streaming is done.
1575extern "C" fn stream_done_callback(_user_data: *mut c_void) {
1576    // Nothing to do - state cleanup happens in stream_response
1577}
1578
1579/// Callback invoked on error during streaming.
1580extern "C" fn stream_error_callback(user_data: *mut c_void, code: c_int, message: *const c_char) {
1581    if user_data.is_null() {
1582        return;
1583    }
1584
1585    let state = unsafe { &*(user_data as *const StreamState) };
1586    let msg = if message.is_null() {
1587        "Streaming error occurred (no message provided by Swift)".to_string()
1588    } else {
1589        unsafe { CStr::from_ptr(message).to_string_lossy().into_owned() }
1590    };
1591
1592    if let Ok(mut error) = state.error.lock() {
1593        error.get_or_insert((code, msg));
1594    }
1595}
1596
1597/// Callback invoked when a tool needs to be called during session operations.
1598/// This is used by Swift's `FFITool` to call back into Rust.
1599extern "C" fn session_tool_callback(
1600    user_data: *mut c_void,
1601    tool_name: *const c_char,
1602    arguments_json: *const c_char,
1603) -> *mut c_char {
1604    if user_data.is_null() || tool_name.is_null() {
1605        let result = ToolResult::error("Invalid callback parameters");
1606        return string_to_c(result.to_json());
1607    }
1608
1609    // user_data is a raw pointer to Arc<ToolCallbackData> (from Arc::into_raw)
1610    // SAFETY: Swift's ToolDispatcher holds a strong reference to this Arc and
1611    // is the object invoking this callback, so ARC keeps the data alive for
1612    // the duration of the call. We must NOT consume the Arc here - just
1613    // borrow it.
1614    let callback_data = unsafe { &*(user_data as *const ToolCallbackData) };
1615
1616    let name = unsafe { CStr::from_ptr(tool_name).to_string_lossy().into_owned() };
1617    let args_str = if arguments_json.is_null() {
1618        "{}".to_string()
1619    } else {
1620        unsafe {
1621            CStr::from_ptr(arguments_json)
1622                .to_string_lossy()
1623                .into_owned()
1624        }
1625    };
1626
1627    // Parse arguments (with a best-effort auto-close for truncated JSON)
1628    let arguments: serde_json::Value = match parse_tool_arguments(&args_str) {
1629        Ok(v) => v,
1630        Err(message) => {
1631            let result = ToolResult::error(message);
1632            return string_to_c(result.to_json());
1633        }
1634    };
1635
1636    // Find and call the tool
1637    let Ok(tools) = callback_data.tools.lock() else {
1638        let result = ToolResult::error("Failed to acquire tool lock");
1639        return string_to_c(result.to_json());
1640    };
1641
1642    let Some(tool) = tools.get(&name).map(Arc::clone) else {
1643        let result = ToolResult::error(format!("Unknown tool: {name}"));
1644        return string_to_c(result.to_json());
1645    };
1646
1647    // Release the lock before calling the tool (it might take a while)
1648    drop(tools);
1649
1650    // Invoke the tool. A panic here would unwind into Swift and abort the
1651    // process; report it as a tool error so the model (and caller) can react.
1652    let result =
1653        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| tool.call(arguments))) {
1654            Ok(Ok(output)) => ToolResult::success(output),
1655            Ok(Err(e)) => ToolResult::error(e.to_string()),
1656            Err(_) => ToolResult::error(format!("Tool '{name}' panicked")),
1657        };
1658
1659    string_to_c(result.to_json())
1660}
1661
1662/// Copies a Swift-allocated (`strdup`) C string and always frees it, even
1663/// when the contents are not valid UTF-8.
1664///
1665/// # Safety
1666///
1667/// `ptr` must be a non-null, NUL-terminated allocation owned by the caller
1668/// and freeable with `fm_string_free`.
1669unsafe fn take_swift_string(
1670    ptr: *mut c_char,
1671    make_error: impl FnOnce(std::str::Utf8Error) -> Error,
1672) -> Result<String> {
1673    let converted = unsafe { CStr::from_ptr(ptr) }.to_str().map(str::to_owned);
1674    unsafe { ffi::fm_string_free(ptr) };
1675    converted.map_err(make_error)
1676}
1677
1678/// Helper to convert a Rust string to a C string that can be freed by Swift.
1679fn string_to_c(s: String) -> *mut c_char {
1680    match CString::new(s) {
1681        Ok(cs) => cs.into_raw(),
1682        Err(_) => ptr::null_mut(),
1683    }
1684}
1685
1686fn parse_tool_arguments(input: &str) -> std::result::Result<serde_json::Value, String> {
1687    match serde_json::from_str(input) {
1688        Ok(value) => Ok(value),
1689        Err(err) => {
1690            if let Some(fixed) = autoclose_json(input) {
1691                match serde_json::from_str(&fixed) {
1692                    Ok(value) => Ok(value),
1693                    Err(fixed_err) => Err(format!(
1694                        "Failed to parse arguments: {err}; attempted fix: {fixed_err}"
1695                    )),
1696                }
1697            } else {
1698                Err(format!("Failed to parse arguments: {err}"))
1699            }
1700        }
1701    }
1702}
1703
1704fn timeout_millis(timeout: Duration) -> Result<u64> {
1705    let milliseconds = u64::try_from(timeout.as_millis()).map_err(|_| {
1706        Error::InvalidInput("Timeout is too large to represent in milliseconds".to_string())
1707    })?;
1708
1709    if timeout.is_zero() {
1710        Ok(0)
1711    } else {
1712        Ok(milliseconds.max(1))
1713    }
1714}
1715
1716fn json_timeout_millis(timeout: Duration) -> Result<Option<u64>> {
1717    if timeout.is_zero() {
1718        Ok(None)
1719    } else {
1720        timeout_millis(timeout).map(Some)
1721    }
1722}
1723
1724/// Maximum input size for `autoclose_json` to prevent resource exhaustion (1 MB).
1725const AUTOCLOSE_JSON_MAX_SIZE: usize = 1024 * 1024;
1726
1727fn autoclose_json(input: &str) -> Option<String> {
1728    // Limit input size to prevent resource exhaustion attacks
1729    if input.len() > AUTOCLOSE_JSON_MAX_SIZE {
1730        return None;
1731    }
1732
1733    let mut stack: Vec<char> = Vec::new();
1734    let mut in_string = false;
1735    let mut escape = false;
1736
1737    for ch in input.chars() {
1738        if in_string {
1739            if escape {
1740                escape = false;
1741                continue;
1742            }
1743            if ch == '\\' {
1744                escape = true;
1745                continue;
1746            }
1747            if ch == '"' {
1748                in_string = false;
1749            }
1750            continue;
1751        }
1752
1753        match ch {
1754            '"' => in_string = true,
1755            '{' => stack.push('}'),
1756            '[' => stack.push(']'),
1757            '}' if stack.pop() != Some('}') => return None,
1758            ']' if stack.pop() != Some(']') => return None,
1759            _ => {}
1760        }
1761    }
1762
1763    if in_string || stack.is_empty() {
1764        return None;
1765    }
1766
1767    let mut out = input.to_string();
1768    while let Some(close) = stack.pop() {
1769        out.push(close);
1770    }
1771    Some(out)
1772}
1773
1774#[cfg(test)]
1775mod tests {
1776    use std::ffi::{CString, c_void};
1777    use std::ptr::NonNull;
1778    use std::sync::Mutex;
1779    use std::time::Duration;
1780
1781    use crate::error::Error;
1782    use crate::session::{
1783        Attachment, Response, SessionUsage, StreamState, SystemTool, attachment_specs,
1784        json_timeout_millis, session_usage_from_json, stream_error_callback, system_tools_json,
1785        timeout_millis,
1786    };
1787
1788    #[test]
1789    fn test_response() {
1790        let response = Response::with_usage("Hello, world!".to_string(), None);
1791        assert_eq!(response.content(), "Hello, world!");
1792        assert_eq!(response.as_ref(), "Hello, world!");
1793        assert_eq!(format!("{response}"), "Hello, world!");
1794        assert_eq!(response.into_content(), "Hello, world!");
1795    }
1796
1797    #[test]
1798    fn stream_error_callback_preserves_an_existing_callback_error() {
1799        let mut state = StreamState {
1800            session_ptr: NonNull::dangling(),
1801            on_chunk: Mutex::new(Box::new(|_: &str| {})),
1802            error: Mutex::new(Some((
1803                crate::ffi::ErrorCode::Unknown as i32,
1804                "Stream chunk callback panicked".to_string(),
1805            ))),
1806        };
1807        let message = CString::new("Cancelled").expect("literal has no NUL");
1808
1809        stream_error_callback(
1810            std::ptr::from_mut(&mut state).cast::<c_void>(),
1811            crate::ffi::ErrorCode::Cancelled as i32,
1812            message.as_ptr(),
1813        );
1814
1815        let error = state.error.lock().expect("stream error mutex should lock");
1816        assert_eq!(
1817            error.as_ref().map(|(_, message)| message.as_str()),
1818            Some("Stream chunk callback panicked")
1819        );
1820    }
1821
1822    #[test]
1823    fn timeout_millis_rejects_values_larger_than_u64() {
1824        let timeout = Duration::from_secs(u64::MAX);
1825        assert!(matches!(
1826            timeout_millis(timeout),
1827            Err(Error::InvalidInput(_))
1828        ));
1829    }
1830
1831    #[test]
1832    fn timeout_millis_preserves_zero_and_rounds_positive_sub_millisecond_values_up() {
1833        assert!(matches!(timeout_millis(Duration::ZERO), Ok(0)));
1834
1835        for timeout in [
1836            Duration::from_nanos(1),
1837            Duration::from_micros(500),
1838            Duration::from_micros(999),
1839        ] {
1840            assert!(matches!(timeout_millis(timeout), Ok(1)));
1841        }
1842
1843        assert!(matches!(timeout_millis(Duration::from_millis(1)), Ok(1)));
1844    }
1845
1846    const _: fn(
1847        &crate::Session,
1848        &str,
1849        &serde_json::Value,
1850        &crate::GenerationOptions,
1851        Duration,
1852    ) -> crate::Result<Response> = crate::Session::respond_json_with_timeout;
1853
1854    #[test]
1855    fn respond_json_with_timeout_zero_selects_existing_json_path() {
1856        assert!(matches!(json_timeout_millis(Duration::ZERO), Ok(None)));
1857    }
1858
1859    #[test]
1860    fn respond_json_with_timeout_rounds_positive_sub_millisecond_values_up() {
1861        for timeout in [
1862            Duration::from_nanos(1),
1863            Duration::from_micros(500),
1864            Duration::from_micros(999),
1865        ] {
1866            assert!(matches!(json_timeout_millis(timeout), Ok(Some(1))));
1867        }
1868
1869        assert!(matches!(
1870            json_timeout_millis(Duration::from_millis(1)),
1871            Ok(Some(1))
1872        ));
1873    }
1874
1875    #[test]
1876    fn respond_json_with_timeout_reuses_timeout_overflow_error() {
1877        let timeout = Duration::from_secs(u64::MAX);
1878        assert!(matches!(
1879            json_timeout_millis(timeout),
1880            Err(Error::InvalidInput(_))
1881        ));
1882    }
1883
1884    #[test]
1885    fn session_usage_should_parse_all_counters() {
1886        let usage = session_usage_from_json(
1887            r#"{"inputTokens":120,"cachedInputTokens":48,"outputTokens":64,"reasoningTokens":16}"#,
1888        )
1889        .expect("session usage JSON should parse");
1890
1891        assert_eq!(usage.input_tokens, 120);
1892        assert_eq!(usage.cached_input_tokens, 48);
1893        assert_eq!(usage.output_tokens, 64);
1894        assert_eq!(usage.reasoning_tokens, 16);
1895    }
1896
1897    #[test]
1898    fn session_usage_should_reject_negative_counters() {
1899        let err = session_usage_from_json(
1900            r#"{"inputTokens":-1,"cachedInputTokens":0,"outputTokens":0,"reasoningTokens":0}"#,
1901        )
1902        .expect_err("negative token counts should fail");
1903        assert!(matches!(err, Error::InternalError(_)));
1904    }
1905
1906    #[test]
1907    fn session_usage_should_reject_invalid_json() {
1908        let err = session_usage_from_json("not json").expect_err("invalid JSON should fail");
1909        assert!(matches!(err, Error::InternalError(_)));
1910    }
1911
1912    #[test]
1913    fn response_should_expose_optional_usage() {
1914        let usage = SessionUsage {
1915            input_tokens: 10,
1916            cached_input_tokens: 1,
1917            output_tokens: 5,
1918            reasoning_tokens: 0,
1919        };
1920        let response = Response::with_usage("ok".to_string(), Some(usage));
1921        assert_eq!(response.usage(), Some(usage));
1922
1923        let response = Response::with_usage("ok".to_string(), None);
1924        assert_eq!(response.usage(), None);
1925    }
1926
1927    #[test]
1928    fn session_usage_delta_should_subtract_counters() {
1929        let earlier = SessionUsage {
1930            input_tokens: 100,
1931            cached_input_tokens: 40,
1932            output_tokens: 50,
1933            reasoning_tokens: 10,
1934        };
1935        let later = SessionUsage {
1936            input_tokens: 180,
1937            cached_input_tokens: 90,
1938            output_tokens: 75,
1939            reasoning_tokens: 30,
1940        };
1941
1942        let delta = later
1943            .delta_since(&earlier)
1944            .expect("in-order snapshots should subtract");
1945        assert_eq!(delta.input_tokens, 80);
1946        assert_eq!(delta.cached_input_tokens, 50);
1947        assert_eq!(delta.output_tokens, 25);
1948        assert_eq!(delta.reasoning_tokens, 20);
1949    }
1950
1951    #[test]
1952    fn session_usage_delta_should_reject_backwards_counters() {
1953        let earlier = SessionUsage {
1954            input_tokens: 100,
1955            cached_input_tokens: 0,
1956            output_tokens: 0,
1957            reasoning_tokens: 0,
1958        };
1959        let later = SessionUsage {
1960            input_tokens: 50,
1961            cached_input_tokens: 0,
1962            output_tokens: 0,
1963            reasoning_tokens: 0,
1964        };
1965
1966        let err = later
1967            .delta_since(&earlier)
1968            .expect_err("backwards counters should fail");
1969        assert!(matches!(err, Error::InvalidInput(_)));
1970    }
1971
1972    #[test]
1973    fn attachment_specs_should_index_buffers_and_keep_labels() {
1974        let bytes = [0_u8, 1, 2, 3];
1975        let attachments = [
1976            Attachment::file("/tmp/photo.png").with_label("photo"),
1977            Attachment::image_bytes(&bytes),
1978        ];
1979
1980        let (json, buffers, buffer_lens) =
1981            attachment_specs(&attachments).expect("attachment specs should serialize");
1982
1983        assert_eq!(
1984            json,
1985            r#"[{"kind":"file","path":"/tmp/photo.png","label":"photo"},{"kind":"data","bufferIndex":0}]"#
1986        );
1987        assert_eq!(buffers, vec![bytes.as_ptr()]);
1988        assert_eq!(buffer_lens, vec![bytes.len()]);
1989    }
1990
1991    #[test]
1992    fn attachment_specs_should_reject_non_utf8_paths() {
1993        use std::ffi::OsString;
1994        use std::os::unix::ffi::OsStringExt;
1995
1996        let path = std::path::PathBuf::from(OsString::from_vec(vec![0x66, 0x6f, 0x80]));
1997        let attachments = [Attachment::file(path)];
1998        let err = attachment_specs(&attachments).expect_err("non-UTF-8 path should fail");
1999        assert!(matches!(err, Error::InvalidInput(_)));
2000    }
2001
2002    #[test]
2003    fn system_tools_should_reject_duplicates() {
2004        let err = system_tools_json(&[SystemTool::Ocr, SystemTool::Ocr])
2005            .expect_err("duplicate built-in tools should fail");
2006        assert!(matches!(err, Error::InvalidInput(_)));
2007    }
2008}