Skip to main content

troupekit_ffi_core/
records.rs

1/// Token counts and cost of a run or step, as plain numbers.
2/// `cost_usd_micros` is millionths of a US dollar from the model price;
3/// host models are free unless priced with `host_model_priced`.
4#[non_exhaustive]
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub struct FfiUsage {
7    pub input_tokens: u64,
8    pub output_tokens: u64,
9    pub cost_usd_micros: u64,
10}
11
12/// Result of one finished agent run: the answer `text`, the typed
13/// output as JSON text (`output_json`), `usage`, the number of model
14/// calls and the run id text.
15#[non_exhaustive]
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct RunResult {
18    pub text: String,
19    pub output_json: String,
20    pub usage: FfiUsage,
21    pub model_calls: u32,
22    pub run_id: String,
23}
24
25impl RunResult {
26    /// Copies a kit run outcome into a plain record: the typed output
27    /// becomes JSON text and the run id its text form.
28    /// Output: the record.
29    pub(crate) fn from_outcome(outcome: &troupekit_kit::RunOutcome) -> RunResult {
30        RunResult {
31            text: outcome.text().to_string(),
32            output_json: outcome.output().to_string(),
33            usage: crate::stream::usage_of(outcome.usage()),
34            model_calls: outcome.model_calls(),
35            run_id: outcome.run_id().to_string(),
36        }
37    }
38}
39
40/// Result of one finished graph run: the last node's output and the
41/// whole state as JSON text, `usage`, the steps taken and the run id
42/// text.
43#[non_exhaustive]
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
45pub struct GraphResult {
46    pub output_json: String,
47    pub state_json: String,
48    pub usage: FfiUsage,
49    pub steps: u64,
50    pub run_id: String,
51}
52
53/// Where a run stands after one `resume_for` window: `Done` with the
54/// answer text, or `Pending` when the budget ran out first; the run
55/// then continues from its last checkpoint on the next call.
56#[non_exhaustive]
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum Progress {
59    Done { text: String },
60    Pending { run_id: String },
61}
62
63impl Progress {
64    /// Copies a kit `Progress` into the neutral one.
65    /// Output: `Done` or `Pending`, or `Internal` for a kit state added
66    /// later that has no neutral form yet.
67    pub(crate) fn from_kit(progress: troupekit_kit::Progress) -> Result<Progress, crate::FfiError> {
68        match progress {
69            troupekit_kit::Progress::Done(text) => Ok(Progress::Done { text }),
70            troupekit_kit::Progress::Pending { run_id } => Ok(Progress::Pending {
71                run_id: run_id.to_string(),
72            }),
73            #[allow(unreachable_patterns)]
74            _ => Err(crate::FfiError::new(
75                crate::ErrorCode::Internal,
76                "resume_for returned a progress state this version does not know",
77            )),
78        }
79    }
80}
81
82/// Why a run paused: a graph node waits for an approval or an answer,
83/// or a budget `limit` (`call`, `run`, a period) would be passed.
84/// Resume after the host has dealt with it.
85#[non_exhaustive]
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum FfiPause {
88    Approval { node: String },
89    Question { node: String },
90    Budget { limit: String },
91}
92
93/// What happened in one event, mirroring the engine's event bodies:
94/// run and step lifecycle, text deltas, tool calls, pauses, the end.
95/// Hosts match it with a fallback arm, since new kinds may be added.
96#[non_exhaustive]
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub enum FfiEventKind {
99    RunStarted {
100        workflow: String,
101    },
102    StepStarted {
103        step: String,
104        persona: Option<String>,
105    },
106    TextDelta {
107        text: String,
108    },
109    ToolCallStarted {
110        call_id: String,
111        name: String,
112    },
113    ToolCallFinished {
114        call_id: String,
115        is_error: bool,
116    },
117    StepFinished {
118        step: String,
119        usage: FfiUsage,
120    },
121    RunPaused {
122        reason: FfiPause,
123    },
124    RunFinished {
125        usage: FfiUsage,
126    },
127    RunFailed {
128        error: String,
129    },
130}
131
132/// One event of a run: its run id text, its `seq` (ordered within one
133/// run id), the clock time in milliseconds since the Unix epoch, and
134/// the `kind`. Delivered by `RunStream::next` or an `EventListener`.
135#[non_exhaustive]
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct FfiEvent {
138    pub run_id: String,
139    pub seq: u64,
140    pub at_ms: i64,
141    pub kind: FfiEventKind,
142}
143
144/// What a host model can do: native tool calls (`tools`), JSON Schema
145/// constrained output (`json_schema`), token streaming (`streaming`)
146/// and its context window in tokens. Default: none, 4096 tokens.
147#[non_exhaustive]
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub struct HostModelCaps {
150    pub tools: bool,
151    pub json_schema: bool,
152    pub streaming: bool,
153    pub context_tokens: u32,
154}
155
156impl Default for HostModelCaps {
157    /// Returns the most limited model: no native tools, no schema, no
158    /// streaming, a 4096-token context. Hosts switch on what their model
159    /// supports, field by field.
160    fn default() -> Self {
161        HostModelCaps {
162            tools: false,
163            json_schema: false,
164            streaming: false,
165            context_tokens: 4096,
166        }
167    }
168}
169
170/// One message of a host model request: `role` (`user`, `assistant`,
171/// `tool`), its `text`, the assistant's tool calls as JSON text, and the
172/// tool call id a `tool` message answers.
173#[non_exhaustive]
174#[derive(Clone, Debug, Default, PartialEq, Eq)]
175pub struct HostMessage {
176    pub role: String,
177    pub text: String,
178    pub tool_calls_json: Option<String>,
179    pub tool_call_id: Option<String>,
180}
181
182/// One request to a host model: the system prompt, the conversation,
183/// the tools as a JSON array, the output JSON Schema, and the reply's
184/// token cap. Built by troupekit, read by the host.
185#[non_exhaustive]
186#[derive(Clone, Debug, Default, PartialEq, Eq)]
187pub struct HostRequest {
188    pub system: Option<String>,
189    pub messages: Vec<HostMessage>,
190    pub tools_json: Option<String>,
191    pub schema_json: Option<String>,
192    pub max_tokens: u32,
193}
194
195/// A host model's reply: the whole `text` (also when it was streamed
196/// through `TokenSink`), the token counts the model reported, and for a
197/// model with native tools its calls as a JSON list of `{id, name,
198/// arguments}`. Start from `HostReply::default()` and set the fields.
199#[non_exhaustive]
200#[derive(Clone, Debug, Default, PartialEq, Eq)]
201pub struct HostReply {
202    pub text: String,
203    pub input_tokens: u64,
204    pub output_tokens: u64,
205    pub tool_calls_json: Option<String>,
206}
207
208const SECRET_HEADERS: [&str; 4] = [
209    "authorization",
210    "proxy-authorization",
211    "x-api-key",
212    "x-goog-api-key",
213];
214
215/// One HTTP header: name, value, and `sensitive`, set when the value is
216/// a credential such as the vendor API key. `Debug` shows a sensitive
217/// value as `[redacted]`; adapters must hide it in their text forms too.
218#[non_exhaustive]
219#[derive(Clone, Default, PartialEq, Eq)]
220pub struct HostHeader {
221    pub name: String,
222    pub value: String,
223    pub sensitive: bool,
224}
225
226impl HostHeader {
227    /// Builds a header from `name` and `value`. `sensitive` is set for
228    /// the credential headers `authorization`, `proxy-authorization`,
229    /// `x-api-key` and `x-goog-api-key`, in any case. Output: the header.
230    pub fn new(name: impl Into<String>, value: impl Into<String>) -> HostHeader {
231        let name = name.into();
232        let sensitive = is_secret_name(&name);
233        HostHeader {
234            name,
235            value: value.into(),
236            sensitive,
237        }
238    }
239
240    fn hidden(&self) -> bool {
241        self.sensitive || is_secret_name(&self.name)
242    }
243}
244
245impl std::fmt::Debug for HostHeader {
246    /// Writes the header with its value replaced by `[redacted]` when it
247    /// is sensitive or named like a credential header, so logging a
248    /// request never prints the API key.
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        let value: &dyn std::fmt::Debug = if self.hidden() {
251            &"[redacted]"
252        } else {
253            &self.value
254        };
255        f.debug_struct("HostHeader")
256            .field("name", &self.name)
257            .field("value", value)
258            .field("sensitive", &self.sensitive)
259            .finish()
260    }
261}
262
263fn is_secret_name(name: &str) -> bool {
264    SECRET_HEADERS
265        .iter()
266        .any(|secret| name.eq_ignore_ascii_case(secret))
267}
268
269/// One HTTP request a host transport sends: method, absolute URL,
270/// headers and body bytes, only for model and embedding calls to the
271/// resolved vendor. The key header is `sensitive`; `Debug` redacts it.
272#[non_exhaustive]
273#[derive(Clone, Debug, Default, PartialEq, Eq)]
274pub struct HostHttpRequest {
275    pub method: String,
276    pub url: String,
277    pub headers: Vec<HostHeader>,
278    pub body: Vec<u8>,
279}
280
281/// A failure inside host code, as a message. Foreign exceptions arrive
282/// as this type from the adapters. A host tool's error reaches the model
283/// as an error result; a host model's error fails the run with
284/// `HostCallback`; a host transport's error is retried (`Retries`).
285#[non_exhaustive]
286#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
287#[error("{message}")]
288pub struct HostError {
289    pub message: String,
290}
291
292impl HostError {
293    /// Builds a host error from `message`.
294    /// Input: any text; it is shown to the developer and may reach the
295    /// model for a tool error. Output: the error.
296    pub fn new(message: impl Into<String>) -> HostError {
297        HostError {
298            message: message.into(),
299        }
300    }
301}
302
303/// Knowledge settings for `AgentBuilder::knowledge`: the document
304/// `dir` to ingest at build, an optional index and store path, and
305/// whether files that fail to load are allowed.
306#[cfg(feature = "knowledge")]
307#[non_exhaustive]
308#[derive(Clone, Debug, Default, PartialEq, Eq)]
309pub struct KnowledgeConfig {
310    pub dir: String,
311    pub index: Option<String>,
312    pub store: Option<String>,
313    pub allow_failed: bool,
314}
315
316#[cfg(feature = "knowledge")]
317impl KnowledgeConfig {
318    /// Builds knowledge settings for the document directory `dir`.
319    /// Other fields keep their defaults: no index or store path, and a
320    /// file that fails to load fails the build.
321    pub fn new(dir: impl Into<String>) -> KnowledgeConfig {
322        KnowledgeConfig {
323            dir: dir.into(),
324            ..KnowledgeConfig::default()
325        }
326    }
327}
328
329/// Memory settings for `AgentBuilder::memory`: the `user` and `session`
330/// the facts belong to, an optional SQLite path, and whether known facts
331/// are put in the system prompt (`preamble`).
332#[cfg(feature = "knowledge")]
333#[non_exhaustive]
334#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct MemoryConfig {
336    pub user: String,
337    pub session: String,
338    pub sqlite: Option<String>,
339    pub preamble: bool,
340}
341
342#[cfg(feature = "knowledge")]
343impl MemoryConfig {
344    /// Builds memory settings for `user` and `session`, both set by the
345    /// host. Other fields keep the kit's defaults: the agent's own store
346    /// and the preamble on.
347    pub fn new(user: impl Into<String>, session: impl Into<String>) -> MemoryConfig {
348        MemoryConfig {
349            user: user.into(),
350            session: session.into(),
351            sqlite: None,
352            preamble: true,
353        }
354    }
355}