iflow-cli-sdk-rust 0.1.6

Rust SDK for iFlow CLI using Agent Client Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::client::IFlowClient;
use crate::error::Result;
use crate::types::{IFlowOptions, Message};
use futures::stream::StreamExt;
use std::time::Duration;
use tokio::time::timeout;

/// Simple synchronous query to iFlow
///
/// Sends a query to iFlow and waits for a complete response.
/// This is a convenience function for simple request-response interactions.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
///
/// # Returns
/// * `Ok(String)` containing the response from iFlow
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::query;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let response = query("What is 2 + 2?").await?;
///     println!("{}", response);
///     Ok(())
/// }
/// ```
pub async fn query(prompt: &str) -> Result<String> {
    let default_timeout = IFlowOptions::default().timeout;
    query_with_timeout(prompt, default_timeout).await
}

/// Simple synchronous query to iFlow with custom options
///
/// Sends a query to iFlow and waits for a complete response.
/// This is a convenience function for simple request-response interactions.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
/// * `options` - Configuration options for the query
///
/// # Returns
/// * `Ok(String)` containing the response from iFlow
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::{query_with_config, IFlowOptions};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let options = IFlowOptions::new().with_timeout(120.0);
///     let response = query_with_config("What is 2 + 2?", options).await?;
///     println!("{}", response);
///     Ok(())
/// }
/// ```
pub async fn query_with_config(prompt: &str, options: IFlowOptions) -> Result<String> {
    // Apply timeout to the entire operation
    let timeout_secs = options.timeout;
    // Use a fraction of the total timeout for individual message reception
    // This ensures we don't block indefinitely on any single message
    let message_timeout_secs = (timeout_secs / 10.0).min(1.0).max(0.1);

    match timeout(Duration::from_secs_f64(timeout_secs), async {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                tracing::debug!("Creating IFlowClient with custom options");
                let mut client = IFlowClient::new(Some(options));
                tracing::debug!("Connecting to iFlow...");
                client.connect().await?;
                tracing::debug!("Connected to iFlow");

                tracing::debug!("Sending message: {}", prompt);
                client.send_message(prompt, None).await?;
                tracing::debug!("Message sent");

                let mut response = String::new();
                let mut message_stream = client.messages();

                // First wait for the send_message to complete by receiving the TaskFinish message
                // The send_message function sends a TaskFinish message when the prompt is complete
                let mut prompt_finished = false;
                while !prompt_finished {
                    match timeout(
                        Duration::from_secs_f64(message_timeout_secs),
                        message_stream.next(),
                    )
                    .await
                    {
                        Ok(Some(message)) => {
                            tracing::debug!("Received message: {:?}", message);
                            match message {
                                Message::Assistant { content } => {
                                    response.push_str(&content);
                                }
                                Message::TaskFinish { .. } => {
                                    prompt_finished = true;
                                }
                                _ => {}
                            }
                        }
                        Ok(None) => {
                            // Stream ended
                            tracing::debug!("Message stream ended");
                            prompt_finished = true;
                        }
                        Err(_) => {
                            // Timeout on individual message - this is expected during normal operation
                            // Continue the loop to check if we should still wait
                            // The outer timeout will catch if we've exceeded the total time
                        }
                    }
                }
                tracing::debug!("Query completed, response length: {}", response.len());

                client.disconnect().await?;
                Ok(response.trim().to_string())
            })
            .await
    })
    .await
    {
        Ok(result) => result,
        Err(_) => Err(crate::error::IFlowError::Timeout(
            "Operation timed out".to_string(),
        )),
    }
}

/// Simple synchronous query to iFlow with custom timeout
///
/// Sends a query to iFlow and waits for a complete response.
/// This is a convenience function for simple request-response interactions.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
/// * `timeout_secs` - Timeout in seconds
///
/// # Returns
/// * `Ok(String)` containing the response from iFlow
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::query_with_timeout;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let response = query_with_timeout("What is 2 + 2?", 120.0).await?;
///     println!("{}", response);
///     Ok(())
/// }
/// ```
pub async fn query_with_timeout(prompt: &str, timeout_secs: f64) -> Result<String> {
    // Apply timeout to the entire operation
    // Use a fraction of the total timeout for individual message reception
    // This ensures we don't block indefinitely on any single message
    let message_timeout_secs = (timeout_secs / 10.0).min(1.0).max(0.1);

    match timeout(Duration::from_secs_f64(timeout_secs), async {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                // Create client with the specified timeout and auto-start configuration for stdio mode
                let options = IFlowOptions::new()
                    .with_timeout(timeout_secs)
                    .with_process_config(
                        crate::types::ProcessConfig::new()
                            .enable_auto_start()
                            .stdio_mode(),
                    );
                tracing::debug!(
                    "Creating IFlowClient with options: auto_start={}, start_port={:?}",
                    options.process.auto_start,
                    options.process.start_port
                );
                let mut client = IFlowClient::new(Some(options));
                tracing::debug!("Connecting to iFlow...");
                client.connect().await?;
                tracing::debug!("Connected to iFlow");

                tracing::debug!("Sending message: {}", prompt);
                client.send_message(prompt, None).await?;
                tracing::debug!("Message sent");

                let mut response = String::new();
                let mut message_stream = client.messages();

                // First wait for the send_message to complete by receiving the TaskFinish message
                // The send_message function sends a TaskFinish message when the prompt is complete
                let mut prompt_finished = false;
                while !prompt_finished {
                    match timeout(
                        Duration::from_secs_f64(message_timeout_secs),
                        message_stream.next(),
                    )
                    .await
                    {
                        Ok(Some(message)) => {
                            tracing::debug!("Received message: {:?}", message);
                            match message {
                                Message::Assistant { content } => {
                                    response.push_str(&content);
                                }
                                Message::TaskFinish { .. } => {
                                    prompt_finished = true;
                                }
                                _ => {}
                            }
                        }
                        Ok(None) => {
                            // Stream ended
                            tracing::debug!("Message stream ended");
                            prompt_finished = true;
                        }
                        Err(_) => {
                            // Timeout on individual message - this is expected during normal operation
                            // Continue the loop to check if we should still wait
                            // The outer timeout will catch if we've exceeded the total time
                        }
                    }
                }
                tracing::debug!("Query completed, response length: {}", response.len());

                client.disconnect().await?;
                Ok(response.trim().to_string())
            })
            .await
    })
    .await
    {
        Ok(result) => result,
        Err(_) => Err(crate::error::IFlowError::Timeout(
            "Operation timed out".to_string(),
        )),
    }
}

/// Stream responses from iFlow
///
/// Sends a query to iFlow and returns a stream of response chunks.
/// This is useful for real-time output as the response is generated.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
///
/// # Returns
/// * `Ok(impl Stream<Item = String>)` containing the response stream
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::query_stream;
/// use futures::stream::StreamExt;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut stream = query_stream("Tell me a story").await?;
///     
///     while let Some(chunk) = stream.next().await {
///         print!("{}", chunk);
///         // Flush stdout for real-time output
///         use std::io::{self, Write};
///         io::stdout().flush()?;
///     }
///     
///     Ok(())
/// }
/// ```
pub async fn query_stream(prompt: &str) -> Result<impl futures::Stream<Item = String>> {
    query_stream_with_timeout(prompt, 120.0).await
}

/// Stream responses from iFlow with custom options
///
/// Sends a query to iFlow and returns a stream of response chunks.
/// This is useful for real-time output as the response is generated.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
/// * `options` - Configuration options for the query
///
/// # Returns
/// * `Ok(impl Stream<Item = String>)` containing the response stream
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::{query_stream_with_config, IFlowOptions};
/// use futures::stream::StreamExt;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let options = IFlowOptions::new().with_timeout(60.0);
///     let mut stream = query_stream_with_config("Tell me a story", options).await?;
///     
///     while let Some(chunk) = stream.next().await {
///         print!("{}", chunk);
///         // Flush stdout for real-time output
///         use std::io::{self, Write};
///         io::stdout().flush()?;
///     }
///     
///     Ok(())
/// }
/// ```
pub async fn query_stream_with_config(
    prompt: &str,
    options: IFlowOptions,
) -> Result<impl futures::Stream<Item = String>> {
    let local = tokio::task::LocalSet::new();
    // We need to run this in a LocalSet context but return a stream
    // Let's create the client and connection in the LocalSet context
    local
        .run_until(async {
            // Create client with the specified options
            let mut client = IFlowClient::new(Some(options));
            client.connect().await?;

            client.send_message(prompt, None).await?;

            let (tx, rx) = futures::channel::mpsc::unbounded();
            let message_stream = client.messages();

            tokio::task::spawn_local(async move {
                futures::pin_mut!(message_stream);

                while let Some(message) = message_stream.next().await {
                    match message {
                        Message::Assistant { content } => {
                            if tx.unbounded_send(content).is_err() {
                                break;
                            }
                        }
                        Message::TaskFinish { .. } => {
                            break;
                        }
                        _ => {}
                    }
                }

                let _ = client.disconnect().await;
            });

            Ok(rx)
        })
        .await
}

/// Stream responses from iFlow with custom timeout
///
/// Sends a query to iFlow and returns a stream of response chunks.
/// This is useful for real-time output as the response is generated.
///
/// # Arguments
/// * `prompt` - The query prompt to send to iFlow
/// * `timeout_secs` - Timeout in seconds
///
/// # Returns
/// * `Ok(impl Stream<Item = String>)` containing the response stream
/// * `Err(IFlowError)` if there was an error
///
/// # Example
/// ```no_run
/// use iflow_cli_sdk_rust::query_stream_with_timeout;
/// use futures::stream::StreamExt;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut stream = query_stream_with_timeout("Tell me a story", 120.0).await?;
///     
///     while let Some(chunk) = stream.next().await {
///         print!("{}", chunk);
///         // Flush stdout for real-time output
///         use std::io::{self, Write};
///         io::stdout().flush()?;
///     }
///     
///     Ok(())
/// }
/// ```
pub async fn query_stream_with_timeout(
    prompt: &str,
    timeout_secs: f64,
) -> Result<impl futures::Stream<Item = String>> {
    let local = tokio::task::LocalSet::new();
    // We need to run this in a LocalSet context but return a stream
    // Let's create the client and connection in the LocalSet context
    local
        .run_until(async {
            // Create client with the specified timeout
            let options = IFlowOptions::new().with_timeout(timeout_secs);
            let mut client = IFlowClient::new(Some(options));
            client.connect().await?;

            client.send_message(prompt, None).await?;

            let (tx, rx) = futures::channel::mpsc::unbounded();
            let message_stream = client.messages();

            tokio::task::spawn_local(async move {
                futures::pin_mut!(message_stream);

                while let Some(message) = message_stream.next().await {
                    match message {
                        Message::Assistant { content } => {
                            if tx.unbounded_send(content).is_err() {
                                break;
                            }
                        }
                        Message::TaskFinish { .. } => {
                            break;
                        }
                        _ => {}
                    }
                }

                let _ = client.disconnect().await;
            });

            Ok(rx)
        })
        .await
}