Skip to main content

troupekit_ffi/
records.rs

1use std::fmt;
2use troupekit_ffi_core as neutral;
3
4const UNMIRRORED: &str = "troupekit-ffi has no mirror for a new neutral variant";
5
6/// Process-wide settings for `initialize`, mirrored from `RuntimeSettings`.
7/// The neutral layer checks the bounds of plan section 8 (S1 to S3).
8/// Input: worker threads, max caller string bytes, event buffer size.
9#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
10pub struct RuntimeSettings {
11    pub worker_threads: u32,
12    pub max_input_bytes: u64,
13    pub event_buffer: u32,
14}
15
16impl From<RuntimeSettings> for neutral::RuntimeSettings {
17    fn from(value: RuntimeSettings) -> Self {
18        let mut out = neutral::RuntimeSettings::default();
19        out.worker_threads = usize::try_from(value.worker_threads).unwrap_or(usize::MAX);
20        out.max_input_bytes = usize::try_from(value.max_input_bytes).unwrap_or(usize::MAX);
21        out.event_buffer = usize::try_from(value.event_buffer).unwrap_or(usize::MAX);
22        out
23    }
24}
25
26/// Token counts and cost of a step or a run, mirrored from `FfiUsage`.
27/// Output only: built from the neutral value, never read back.
28/// Cost is in millionths of a US dollar.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, uniffi::Record)]
30pub struct Usage {
31    pub input_tokens: u64,
32    pub output_tokens: u64,
33    pub cost_usd_micros: u64,
34}
35
36impl From<neutral::FfiUsage> for Usage {
37    fn from(value: neutral::FfiUsage) -> Self {
38        Usage {
39            input_tokens: value.input_tokens,
40            output_tokens: value.output_tokens,
41            cost_usd_micros: value.cost_usd_micros,
42        }
43    }
44}
45
46/// Result of one agent run, mirrored from `RunResult`.
47/// `output_json` holds the structured output when the agent has a schema.
48/// Output only.
49#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
50pub struct RunResult {
51    pub text: String,
52    pub output_json: String,
53    pub usage: Usage,
54    pub model_calls: u32,
55    pub run_id: String,
56}
57
58impl From<neutral::RunResult> for RunResult {
59    fn from(value: neutral::RunResult) -> Self {
60        RunResult {
61            text: value.text,
62            output_json: value.output_json,
63            usage: value.usage.into(),
64            model_calls: value.model_calls,
65            run_id: value.run_id,
66        }
67    }
68}
69
70/// Result of one graph run, mirrored from `GraphResult`.
71/// Output and state are JSON text, as the neutral layer renders them.
72/// Output only.
73#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
74pub struct GraphResult {
75    pub output_json: String,
76    pub state_json: String,
77    pub usage: Usage,
78    pub steps: u64,
79    pub run_id: String,
80}
81
82impl From<neutral::GraphResult> for GraphResult {
83    fn from(value: neutral::GraphResult) -> Self {
84        GraphResult {
85            output_json: value.output_json,
86            state_json: value.state_json,
87            usage: value.usage.into(),
88            steps: value.steps,
89            run_id: value.run_id,
90        }
91    }
92}
93
94/// Outcome of one background window, mirrored from `Progress`.
95/// `Done` carries the answer; `Pending` the run id to resume next window.
96/// Output only.
97#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)]
98pub enum Progress {
99    Done { text: String },
100    Pending { run_id: String },
101}
102
103impl From<neutral::Progress> for Progress {
104    fn from(value: neutral::Progress) -> Self {
105        match value {
106            neutral::Progress::Done { text } => Progress::Done { text },
107            neutral::Progress::Pending { run_id } => Progress::Pending { run_id },
108            _ => unreachable!("{UNMIRRORED}: Progress"),
109        }
110    }
111}
112
113/// Why a run paused, mirrored from `FfiPause`.
114/// `node` names the graph node; `limit` names the budget that ran out.
115/// Output only.
116#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)]
117pub enum Pause {
118    Approval { node: String },
119    Question { node: String },
120    Budget { limit: String },
121}
122
123impl From<neutral::FfiPause> for Pause {
124    fn from(value: neutral::FfiPause) -> Self {
125        match value {
126            neutral::FfiPause::Approval { node } => Pause::Approval { node },
127            neutral::FfiPause::Question { node } => Pause::Question { node },
128            neutral::FfiPause::Budget { limit } => Pause::Budget { limit },
129            _ => unreachable!("{UNMIRRORED}: FfiPause"),
130        }
131    }
132}
133
134/// What happened in one run event, mirrored from `FfiEventKind`.
135/// Lifecycle kinds are never dropped; `TextDelta` may be when the buffer
136/// is full (`RunStream::dropped_deltas`). Output only.
137#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)]
138pub enum EventKind {
139    RunStarted {
140        workflow: String,
141    },
142    StepStarted {
143        step: String,
144        persona: Option<String>,
145    },
146    TextDelta {
147        text: String,
148    },
149    ToolCallStarted {
150        call_id: String,
151        name: String,
152    },
153    ToolCallFinished {
154        call_id: String,
155        is_error: bool,
156    },
157    StepFinished {
158        step: String,
159        usage: Usage,
160    },
161    RunPaused {
162        reason: Pause,
163    },
164    RunFinished {
165        usage: Usage,
166    },
167    RunFailed {
168        error: String,
169    },
170}
171
172impl From<neutral::FfiEventKind> for EventKind {
173    fn from(value: neutral::FfiEventKind) -> Self {
174        use neutral::FfiEventKind as K;
175        match value {
176            K::RunStarted { workflow } => EventKind::RunStarted { workflow },
177            K::StepStarted { step, persona } => EventKind::StepStarted { step, persona },
178            K::TextDelta { text } => EventKind::TextDelta { text },
179            K::ToolCallStarted { call_id, name } => EventKind::ToolCallStarted { call_id, name },
180            K::ToolCallFinished { call_id, is_error } => {
181                EventKind::ToolCallFinished { call_id, is_error }
182            }
183            K::StepFinished { step, usage } => EventKind::StepFinished {
184                step,
185                usage: usage.into(),
186            },
187            K::RunPaused { reason } => EventKind::RunPaused {
188                reason: reason.into(),
189            },
190            K::RunFinished { usage } => EventKind::RunFinished {
191                usage: usage.into(),
192            },
193            K::RunFailed { error } => EventKind::RunFailed { error },
194            _ => unreachable!("{UNMIRRORED}: FfiEventKind"),
195        }
196    }
197}
198
199/// One run event, mirrored from `FfiEvent`.
200/// `seq` grows by one per event of a run; `at_ms` is Unix time in ms.
201/// Output only.
202#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
203pub struct Event {
204    pub run_id: String,
205    pub seq: u64,
206    pub at_ms: i64,
207    pub kind: EventKind,
208}
209
210impl From<neutral::FfiEvent> for Event {
211    fn from(value: neutral::FfiEvent) -> Self {
212        Event {
213            run_id: value.run_id,
214            seq: value.seq,
215            at_ms: value.at_ms,
216            kind: value.kind.into(),
217        }
218    }
219}
220
221/// What a host model can do, mirrored from `HostModelCaps`.
222/// Returned by the foreign `HostModel::capabilities` and read by Rust.
223/// `context_tokens` is the model's context window.
224#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Record)]
225pub struct HostModelCaps {
226    pub tools: bool,
227    pub json_schema: bool,
228    pub streaming: bool,
229    pub context_tokens: u32,
230}
231
232impl From<HostModelCaps> for neutral::HostModelCaps {
233    fn from(value: HostModelCaps) -> Self {
234        let mut out = neutral::HostModelCaps::default();
235        out.tools = value.tools;
236        out.json_schema = value.json_schema;
237        out.streaming = value.streaming;
238        out.context_tokens = value.context_tokens;
239        out
240    }
241}
242
243/// One message of a host model request, mirrored from `HostMessage`.
244/// Tool calls and the tool call id are JSON and text the Rust side rendered.
245/// Input to the foreign `HostModel::generate`.
246#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
247pub struct HostMessage {
248    pub role: String,
249    pub text: String,
250    pub tool_calls_json: Option<String>,
251    pub tool_call_id: Option<String>,
252}
253
254impl From<neutral::HostMessage> for HostMessage {
255    fn from(value: neutral::HostMessage) -> Self {
256        HostMessage {
257            role: value.role,
258            text: value.text,
259            tool_calls_json: value.tool_calls_json,
260            tool_call_id: value.tool_call_id,
261        }
262    }
263}
264
265/// A request to a host model, mirrored from `HostRequest`.
266/// Rust renders every field; the host passes them to its model as given.
267/// Input to the foreign `HostModel::generate`.
268#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
269pub struct HostRequest {
270    pub system: Option<String>,
271    pub messages: Vec<HostMessage>,
272    pub tools_json: Option<String>,
273    pub schema_json: Option<String>,
274    pub max_tokens: u32,
275}
276
277impl From<neutral::HostRequest> for HostRequest {
278    fn from(value: neutral::HostRequest) -> Self {
279        HostRequest {
280            system: value.system,
281            messages: value.messages.into_iter().map(Into::into).collect(),
282            tools_json: value.tools_json,
283            schema_json: value.schema_json,
284            max_tokens: value.max_tokens,
285        }
286    }
287}
288
289/// A host model's whole reply, mirrored from `HostReply`.
290/// Rust parses and validates `text` and `tool_calls_json` (native tool
291/// calls, for a model whose caps set `tools`); token counts feed usage.
292#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
293pub struct HostReply {
294    pub text: String,
295    pub input_tokens: u64,
296    pub output_tokens: u64,
297    #[uniffi(default = None)]
298    pub tool_calls_json: Option<String>,
299}
300
301impl From<HostReply> for neutral::HostReply {
302    fn from(value: HostReply) -> Self {
303        let mut out = neutral::HostReply::default();
304        out.text = value.text;
305        out.input_tokens = value.input_tokens;
306        out.output_tokens = value.output_tokens;
307        out.tool_calls_json = value.tool_calls_json;
308        out
309    }
310}
311
312/// One HTTP header, mirrored from `HostHeader`.
313/// Used in both directions: request headers out, reply headers back.
314/// `sensitive` marks a credential; every text form shows it as `[redacted]`.
315#[derive(Clone, PartialEq, Eq, uniffi::Record)]
316#[uniffi::export(Debug, Display)]
317pub struct HostHeader {
318    pub name: String,
319    pub value: String,
320    #[uniffi(default = false)]
321    pub sensitive: bool,
322}
323
324impl From<neutral::HostHeader> for HostHeader {
325    fn from(value: neutral::HostHeader) -> Self {
326        HostHeader {
327            name: value.name,
328            value: value.value,
329            sensitive: value.sensitive,
330        }
331    }
332}
333
334impl From<HostHeader> for neutral::HostHeader {
335    /// Builds the neutral header; a header the host marked sensitive stays
336    /// sensitive, and the neutral layer also flags credential header names.
337    /// Input: the mirror. Output: the neutral header.
338    fn from(value: HostHeader) -> Self {
339        let mut header = neutral::HostHeader::new(value.name, value.value);
340        header.sensitive = header.sensitive || value.sensitive;
341        header
342    }
343}
344
345impl fmt::Debug for HostHeader {
346    /// Writes the neutral layer's redacting form, so Kotlin `toString` and
347    /// Swift `debugDescription` never show a credential value.
348    /// Input: the formatter. Output: the neutral `Debug` text.
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        fmt::Debug::fmt(&neutral::HostHeader::from(self.clone()), f)
351    }
352}
353
354impl fmt::Display for HostHeader {
355    /// Same text as `Debug`; Swift `description` and Kotlin `toString`
356    /// read this one. Input: the formatter. Output: the redacted text.
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        fmt::Debug::fmt(self, f)
359    }
360}
361
362/// An HTTP request for a host transport, mirrored from `HostHttpRequest`.
363/// The neutral layer has already checked the URL against the vendor.
364/// Input to the foreign `HostTransport::send`; its text forms redact the key.
365#[derive(Clone, PartialEq, Eq, uniffi::Record)]
366#[uniffi::export(Debug, Display)]
367pub struct HostHttpRequest {
368    pub method: String,
369    pub url: String,
370    pub headers: Vec<HostHeader>,
371    pub body: Vec<u8>,
372}
373
374impl From<neutral::HostHttpRequest> for HostHttpRequest {
375    fn from(value: neutral::HostHttpRequest) -> Self {
376        HostHttpRequest {
377            method: value.method,
378            url: value.url,
379            headers: value.headers.into_iter().map(Into::into).collect(),
380            body: value.body,
381        }
382    }
383}
384
385impl From<HostHttpRequest> for neutral::HostHttpRequest {
386    /// Builds the neutral request, keeping every header's `sensitive` flag.
387    /// Input: the mirror. Output: the neutral request, used for its
388    /// redacting `Debug`.
389    fn from(value: HostHttpRequest) -> Self {
390        let mut request = neutral::HostHttpRequest::default();
391        request.method = value.method;
392        request.url = value.url;
393        request.headers = value.headers.into_iter().map(Into::into).collect();
394        request.body = value.body;
395        request
396    }
397}
398
399impl fmt::Debug for HostHttpRequest {
400    /// Writes the neutral layer's form, with credential headers redacted.
401    /// Input: the formatter. Output: the neutral `Debug` text.
402    /// Swift and Kotlin print this for the request.
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        fmt::Debug::fmt(&neutral::HostHttpRequest::from(self.clone()), f)
405    }
406}
407
408impl fmt::Display for HostHttpRequest {
409    /// Same text as `Debug`, for Swift `description` and Kotlin `toString`.
410    /// Input: the formatter. Output: the redacted text.
411    /// Never shows a credential header value.
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        fmt::Debug::fmt(self, f)
414    }
415}
416
417/// Knowledge settings for an agent, mirrored from `KnowledgeConfig`.
418/// `dir` is the folder to ingest; `index` and `store` are optional paths.
419/// Input to `AgentBuilder::knowledge`.
420#[cfg(feature = "knowledge")]
421#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
422pub struct KnowledgeConfig {
423    pub dir: String,
424    pub index: Option<String>,
425    pub store: Option<String>,
426    pub allow_failed: bool,
427}
428
429#[cfg(feature = "knowledge")]
430impl From<KnowledgeConfig> for neutral::KnowledgeConfig {
431    fn from(value: KnowledgeConfig) -> Self {
432        let mut out = neutral::KnowledgeConfig::new(value.dir);
433        out.index = value.index;
434        out.store = value.store;
435        out.allow_failed = value.allow_failed;
436        out
437    }
438}
439
440/// Memory settings for an agent, mirrored from `MemoryConfig`.
441/// `user` and `session` are set by the host and keep users apart.
442/// Input to `AgentBuilder::memory`.
443#[cfg(feature = "knowledge")]
444#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
445pub struct MemoryConfig {
446    pub user: String,
447    pub session: String,
448    pub sqlite: Option<String>,
449    pub preamble: bool,
450}
451
452#[cfg(feature = "knowledge")]
453impl From<MemoryConfig> for neutral::MemoryConfig {
454    fn from(value: MemoryConfig) -> Self {
455        let mut out = neutral::MemoryConfig::new(value.user, value.session);
456        out.sqlite = value.sqlite;
457        out.preamble = value.preamble;
458        out
459    }
460}