1use 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
18type ToolMapInner = HashMap<String, Arc<dyn Tool>>;
20
21struct ToolCallbackData {
28 tools: Mutex<ToolMapInner>,
29}
30
31#[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 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#[derive(Debug, Clone)]
57pub struct Response {
58 content: String,
59 usage: Option<SessionUsage>,
60}
61
62impl Response {
63 pub(crate) fn with_usage(content: String, usage: Option<SessionUsage>) -> Self {
65 Self { content, usage }
66 }
67
68 pub fn usage(&self) -> Option<SessionUsage> {
73 self.usage
74 }
75
76 pub fn content(&self) -> &str {
78 &self.content
79 }
80
81 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
99pub struct Session {
121 ptr: NonNull<c_void>,
122}
123
124#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub enum SystemTool {
153 Ocr,
158 BarcodeReader,
163 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
177pub 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 #[must_use]
199 pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
200 self.instructions = Some(instructions.into());
201 self
202 }
203
204 #[must_use]
206 pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
207 self.tools.push(tool);
208 self
209 }
210
211 #[must_use]
216 pub fn system_tool(mut self, tool: SystemTool) -> Self {
217 self.system_tools.push(tool);
218 self
219 }
220
221 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 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 pub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self> {
246 Self::create_internal(model, None, &[], &[])
247 }
248
249 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn cancel(&self) {
839 unsafe {
840 ffi::fm_session_cancel(self.ptr.as_ptr());
841 }
842 }
843
844 pub fn cancellation_handle(&self) -> CancellationHandle {
878 unsafe { ffi::fm_session_retain(self.ptr.as_ptr()) };
879 CancellationHandle { ptr: self.ptr }
880 }
881
882 pub fn is_responding(&self) -> bool {
884 unsafe { ffi::fm_session_is_responding(self.ptr.as_ptr()) }
885 }
886
887 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 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 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 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 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 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 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 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 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 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 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 }
1270}
1271
1272unsafe impl Send for Session {}
1275
1276pub struct CancellationHandle {
1288 ptr: NonNull<c_void>,
1289}
1290
1291impl CancellationHandle {
1292 pub fn cancel(&self) {
1300 unsafe { ffi::fm_session_cancel(self.ptr.as_ptr()) };
1301 }
1302
1303 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
1315unsafe impl Send for CancellationHandle {}
1319unsafe impl Sync for CancellationHandle {}
1320
1321type ChunkCallbackFn<'a> = dyn FnMut(&str) + Send + 'a;
1323
1324#[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 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 pub fn image_bytes(bytes: &'a [u8]) -> Attachment<'a> {
1372 Attachment {
1373 source: AttachmentSource::ImageBytes(bytes),
1374 label: None,
1375 }
1376 }
1377
1378 #[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
1400fn 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#[non_exhaustive]
1446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1447pub struct SessionUsage {
1448 pub input_tokens: u64,
1450 pub cached_input_tokens: u64,
1452 pub output_tokens: u64,
1454 pub reasoning_tokens: u64,
1456}
1457
1458impl SessionUsage {
1459 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#[non_exhaustive]
1527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1528pub enum TranscriptErrorHandlingPolicy {
1529 RevertTranscript,
1531 PreserveTranscript,
1533}
1534
1535struct StreamState<'a> {
1537 session_ptr: NonNull<c_void>,
1538 on_chunk: Mutex<Box<ChunkCallbackFn<'a>>>,
1539 error: Mutex<Option<(c_int, String)>>,
1540}
1541
1542extern "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 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 unsafe { ffi::fm_session_cancel(state.session_ptr.as_ptr()) };
1571 }
1572}
1573
1574extern "C" fn stream_done_callback(_user_data: *mut c_void) {
1576 }
1578
1579extern "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
1597extern "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 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 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 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 drop(tools);
1649
1650 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
1662unsafe 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
1678fn 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
1724const AUTOCLOSE_JSON_MAX_SIZE: usize = 1024 * 1024;
1726
1727fn autoclose_json(input: &str) -> Option<String> {
1728 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}