honcho-ai 0.1.4

Rust SDK for Honcho — AI agent memory and social cognition infrastructure
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use std::collections::HashMap;
use std::io::{self, Read};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use chrono::{DateTime, Utc};
use serde_json::Value;
use tokio::io::{AsyncRead, AsyncWriteExt};

use crate::FileSource;
use crate::error::{HonchoError, Result};
use crate::session::PeerSpec;
use crate::types::message::MessageSearchOptions;
use crate::types::session::{SessionConfiguration, SessionPeerConfig};

use super::runtime::block_on;

struct ErrorAwareReader {
    inner: tokio::io::DuplexStream,
    error_slot: Arc<Mutex<Option<io::Error>>>,
}

impl AsyncRead for ErrorAwareReader {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let this = self.get_mut();
        match Pin::new(&mut this.inner).poll_read(cx, buf) {
            Poll::Ready(Ok(())) => {
                if buf.filled().is_empty()
                    && let Some(err) = this.error_slot.lock().ok().and_then(|mut g| g.take())
                {
                    return Poll::Ready(Err(err));
                }
                Poll::Ready(Ok(()))
            }
            other => other,
        }
    }
}

/// Synchronous wrapper around [`crate::Session`].
#[derive(Clone)]
pub struct Session {
    inner: crate::Session,
}

impl std::fmt::Debug for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Session")
            .field("id", &self.inner.id())
            .field("is_active", &self.inner.is_active())
            .finish()
    }
}

impl Session {
    pub(crate) fn new(inner: crate::Session) -> Self {
        Self { inner }
    }

    /// Session's unique identifier.
    #[must_use]
    pub fn id(&self) -> &str {
        self.inner.id()
    }

    /// Whether the session is active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.inner.is_active()
    }

    /// Cached metadata.
    #[must_use]
    pub fn metadata(&self) -> Option<HashMap<String, Value>> {
        self.inner.metadata()
    }

    /// Cached configuration.
    #[must_use]
    pub fn configuration(&self) -> Option<SessionConfiguration> {
        self.inner.configuration()
    }

    /// Refresh cached state from the server.
    pub fn refresh(&self) -> Result<()> {
        block_on(self.inner.refresh())
    }

    /// Fetch and return metadata.
    pub fn get_metadata(&self) -> Result<HashMap<String, Value>> {
        block_on(self.inner.get_metadata())
    }

    /// Set metadata on the server.
    pub fn set_metadata(&self, metadata: HashMap<String, Value>) -> Result<()> {
        block_on(self.inner.set_metadata(metadata))
    }

    /// Fetch and return configuration.
    pub fn get_configuration(&self) -> Result<SessionConfiguration> {
        block_on(self.inner.get_configuration())
    }

    /// Set configuration on the server.
    pub fn set_configuration(&self, configuration: &SessionConfiguration) -> Result<()> {
        block_on(self.inner.set_configuration(configuration))
    }

    /// Fetch configuration as a raw JSON map.
    pub fn get_configuration_raw(&self) -> Result<HashMap<String, Value>> {
        block_on(self.inner.get_configuration_raw())
    }

    /// Set configuration from a raw JSON map.
    pub fn set_configuration_raw(&self, configuration: HashMap<String, Value>) -> Result<()> {
        block_on(self.inner.set_configuration_raw(configuration))
    }

    /// Add a single peer to this session.
    pub fn add_peer(&self, id: impl Into<String>) -> Result<()> {
        block_on(self.inner.add_peer(id))
    }

    /// Add multiple peers.
    pub fn add_peers(&self, specs: impl IntoIterator<Item = impl Into<PeerSpec>>) -> Result<()> {
        block_on(self.inner.add_peers(specs))
    }

    /// Set the complete peer list (replaces existing).
    pub fn set_peers(&self, specs: impl IntoIterator<Item = impl Into<PeerSpec>>) -> Result<()> {
        block_on(self.inner.set_peers(specs))
    }

    /// Remove peers from this session.
    pub fn remove_peers(&self, ids: impl IntoIterator<Item = impl Into<String>>) -> Result<()> {
        block_on(self.inner.remove_peers(ids))
    }

    /// List peers in this session.
    pub fn peers(&self) -> Result<Vec<super::Peer>> {
        block_on(self.inner.peers()).map(|peers| peers.into_iter().map(super::Peer::new).collect())
    }

    /// Get per-peer configuration.
    pub fn get_peer_configuration(&self, peer_id: &str) -> Result<SessionPeerConfig> {
        block_on(self.inner.get_peer_configuration(peer_id))
    }

    /// Set per-peer configuration.
    ///
    /// The peer must already be present in the session. This method does not
    /// create or add peers; use [`Session::add_peer`] or [`Session::add_peers`]
    /// first. If the peer is absent, the server may return 404/`NotFound`.
    pub fn set_peer_configuration(&self, peer_id: &str, config: &SessionPeerConfig) -> Result<()> {
        block_on(self.inner.set_peer_configuration(peer_id, config))
    }

    /// Add messages to this session.
    pub fn add_messages(
        &self,
        messages: Vec<crate::types::message::MessageCreate>,
    ) -> Result<Vec<crate::Message>> {
        block_on(self.inner.add_messages(messages))
    }

    /// List messages, collecting across pages.
    pub fn messages(&self) -> Result<Vec<crate::Message>> {
        block_on(async {
            let page = self.inner.messages().await?;
            super::iter::collect_all_pages(page).await
        })
    }

    /// Delete this session.
    pub fn delete(&self) -> Result<()> {
        block_on(self.inner.delete())
    }

    /// Clone this session.
    pub fn clone_session(&self) -> Result<Session> {
        block_on(self.inner.clone_session()).map(Session::new)
    }

    /// Clone this session up to a message.
    pub fn clone_session_with_message(&self, message_id: &str) -> Result<Session> {
        block_on(self.inner.clone_session_with_message(message_id)).map(Session::new)
    }

    /// Get a single message by ID.
    pub fn get_message(&self, id: &str) -> Result<crate::Message> {
        block_on(self.inner.get_message(id))
    }

    /// Update a message's metadata.
    pub fn update_message(
        &self,
        id: &str,
        metadata: HashMap<String, Value>,
    ) -> Result<crate::Message> {
        block_on(self.inner.update_message(id, metadata))
    }

    /// Get session context.
    pub fn context(&self) -> Result<crate::types::session::SessionContext> {
        block_on(self.inner.context())
    }

    /// Get session context with custom parameters.
    pub fn context_with_options(
        &self,
        options: &crate::types::session::SessionContextOptions,
    ) -> Result<crate::types::session::SessionContext> {
        block_on(self.inner.context_with_options(options))
    }

    /// Get a context builder for fine-grained control over session context parameters.
    pub fn context_builder(&self) -> BlockingSessionContextBuilder {
        BlockingSessionContextBuilder {
            inner: self.inner.context_builder(),
        }
    }

    /// Get available summaries.
    pub fn summaries(&self) -> Result<crate::types::session::SessionSummaries> {
        block_on(self.inner.summaries())
    }

    /// Search messages within this session.
    pub fn search(&self, query: &str) -> Result<Vec<crate::Message>> {
        block_on(self.inner.search(query))
    }

    /// Search messages within this session with custom options.
    pub fn search_with_options(
        &self,
        options: &MessageSearchOptions,
    ) -> Result<Vec<crate::Message>> {
        block_on(self.inner.search_with_options(options))
    }

    /// Get a peer's representation scoped to this session.
    pub fn representation(&self, peer_id: &str) -> Result<String> {
        block_on(self.inner.representation(peer_id))
    }

    /// Get processing queue status for this session.
    pub fn queue_status(
        &self,
        observer_id: Option<&str>,
        sender_id: Option<&str>,
    ) -> Result<crate::types::dream::QueueStatus> {
        block_on(self.inner.queue_status(observer_id, sender_id))
    }

    /// Begin a file upload to this session.
    ///
    /// The API currently accepts `text/plain`, `application/pdf`, and
    /// `application/json`; other MIME types may be rejected by the server.
    ///
    /// Returns a [`BlockingUploadFileBuilder`]. You **must** call `.peer(id)`
    /// and then `.send()` to complete the upload.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(session: &honcho_ai::blocking::Session) -> honcho_ai::error::Result<()> {
    /// let msgs = session
    ///     .upload_file(honcho_ai::FileSource::bytes("doc.pdf", b"data", "application/pdf"))
    ///     .peer("alice")
    ///     .send()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn upload_file(&self, source: impl Into<FileSource>) -> BlockingUploadFileBuilder<'_> {
        BlockingUploadFileBuilder {
            inner: self.inner.upload_file(source),
            reader_handle: None,
        }
    }

    /// Begin a file upload from a synchronous reader.
    ///
    /// The API currently accepts `text/plain`, `application/pdf`, and
    /// `application/json`; other MIME types may be rejected by the server.
    ///
    /// The reader is consumed in a background thread and piped to the async
    /// multipart stream **without buffering the entire file in memory**.
    ///
    /// # Errors
    ///
    /// Returns [`HonchoError::Io`](crate::error::HonchoError::Io) if reading
    /// from `reader` fails during upload.
    pub fn upload_file_streamed(
        &self,
        filename: impl Into<String>,
        reader: impl Read + Send + 'static,
        content_type: impl Into<String>,
    ) -> BlockingUploadFileBuilder<'_> {
        let (mut tx, rx) = tokio::io::duplex(8192);
        let filename_owned = filename.into();
        let content_type_owned = content_type.into();
        let error_slot: Arc<Mutex<Option<io::Error>>> = Arc::new(Mutex::new(None));
        let slot_clone = error_slot.clone();
        let handle = super::runtime::handle();

        let reader_handle = tokio::task::spawn_blocking(move || {
            let mut reader = reader;
            handle.block_on(async {
                let mut buf = [0u8; 8192];
                loop {
                    match reader.read(&mut buf) {
                        Ok(0) => return,
                        Ok(n) => {
                            if tx.write_all(&buf[..n]).await.is_err() {
                                return;
                            }
                        }
                        Err(e) => {
                            let _ = slot_clone.lock().map(|mut g| *g = Some(e));
                            return;
                        }
                    }
                }
            });
        });

        let wrapped_rx = ErrorAwareReader {
            inner: rx,
            error_slot,
        };

        BlockingUploadFileBuilder {
            inner: self.inner.upload_file(FileSource::stream(
                filename_owned,
                wrapped_rx,
                content_type_owned,
            )),
            reader_handle: Some(reader_handle),
        }
    }
}

/// Blocking wrapper around [`crate::UploadFileBuilder`].
pub struct BlockingUploadFileBuilder<'a> {
    inner: crate::UploadFileBuilder<'a>,
    reader_handle: Option<tokio::task::JoinHandle<()>>,
}

impl std::fmt::Debug for BlockingUploadFileBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingUploadFileBuilder")
            .finish_non_exhaustive()
    }
}

impl BlockingUploadFileBuilder<'_> {
    /// Set the peer that owns the uploaded file (required).
    #[must_use]
    pub fn peer(self, id: impl Into<String>) -> Self {
        Self {
            inner: self.inner.peer(id),
            reader_handle: self.reader_handle,
        }
    }

    /// Attach arbitrary JSON metadata to the created message(s).
    #[must_use]
    pub fn metadata(self, value: Value) -> Self {
        Self {
            inner: self.inner.metadata(value),
            reader_handle: self.reader_handle,
        }
    }

    /// Attach configuration to the created message(s).
    #[must_use]
    pub fn configuration(self, value: Value) -> Self {
        Self {
            inner: self.inner.configuration(value),
            reader_handle: self.reader_handle,
        }
    }

    /// Override the creation timestamp (ISO 3339).
    #[must_use]
    pub fn created_at(self, dt: DateTime<Utc>) -> Self {
        Self {
            inner: self.inner.created_at(dt),
            reader_handle: self.reader_handle,
        }
    }

    /// Send the upload request and return the created messages.
    ///
    /// # Errors
    ///
    /// Returns [`HonchoError::Validation`](crate::error::HonchoError::Validation)
    /// if no peer was set via `.peer()`.
    pub fn send(self) -> Result<Vec<crate::Message>> {
        let result = block_on(self.inner.send());

        if let Some(handle) = self.reader_handle {
            let join_result = block_on(handle);
            if result.is_ok()
                && let Err(join_error) = join_result
            {
                return Err(HonchoError::Io(std::io::Error::other(
                    join_error.to_string(),
                )));
            }
        }

        result
    }
}

/// Blocking builder for session representation queries.
///
/// Wraps the async `SessionRepresentationBuilder`.
#[must_use]
pub struct BlockingSessionRepresentationBuilder {
    inner: super::super::session::SessionRepresentationBuilder,
}

impl BlockingSessionRepresentationBuilder {
    /// Set the target peer.
    pub fn target(mut self, target: impl Into<String>) -> Self {
        self.inner = self.inner.target(target);
        self
    }

    /// Set a semantic search query.
    pub fn search_query(mut self, query: impl Into<String>) -> Self {
        self.inner = self.inner.search_query(query);
        self
    }

    /// Set the number of top search results.
    pub fn search_top_k(mut self, k: u32) -> Self {
        self.inner = self.inner.search_top_k(k);
        self
    }

    /// Set the maximum search distance.
    pub fn search_max_distance(mut self, d: f64) -> Self {
        self.inner = self.inner.search_max_distance(d);
        self
    }

    /// Include the most frequent conclusions.
    pub fn include_most_frequent(mut self, v: bool) -> Self {
        self.inner = self.inner.include_most_frequent(v);
        self
    }

    /// Set the maximum number of conclusions.
    pub fn max_conclusions(mut self, m: u32) -> Self {
        self.inner = self.inner.max_conclusions(m);
        self
    }

    /// Execute the request and return the representation.
    pub fn send(self) -> Result<String> {
        block_on(self.inner.send())
    }
}

impl Session {
    /// Get a representation builder for a peer in this session.
    pub fn representation_builder(
        &self,
        peer_id: impl Into<String>,
    ) -> BlockingSessionRepresentationBuilder {
        BlockingSessionRepresentationBuilder {
            inner: self.inner.representation_builder(peer_id.into()),
        }
    }
}

/// Blocking builder for session context queries.
///
/// Wraps the async `SessionContextBuilder`.
#[must_use]
pub struct BlockingSessionContextBuilder {
    inner: crate::session::SessionContextBuilder,
}

impl BlockingSessionContextBuilder {
    /// Whether to include summaries (default: `true`).
    pub fn summary(mut self, val: bool) -> Self {
        self.inner = self.inner.summary(val);
        self
    }

    /// Limit context to this session only (default: `false`).
    pub fn limit_to_session(mut self, val: bool) -> Self {
        self.inner = self.inner.limit_to_session(val);
        self
    }

    /// Maximum number of tokens for the context.
    pub fn tokens(mut self, val: u32) -> Self {
        self.inner = self.inner.tokens(val);
        self
    }

    /// Target peer for perspective-based context.
    pub fn peer_target(mut self, val: impl Into<String>) -> Self {
        self.inner = self.inner.peer_target(val);
        self
    }

    /// Perspective peer for viewing context.
    pub fn peer_perspective(mut self, val: impl Into<String>) -> Self {
        self.inner = self.inner.peer_perspective(val);
        self
    }

    /// Semantic search query to filter relevant conclusions.
    pub fn search_query(mut self, val: impl Into<String>) -> Self {
        self.inner = self.inner.search_query(val);
        self
    }

    /// Number of semantic-search-retrieved conclusions (1–100).
    pub fn search_top_k(mut self, k: u32) -> Self {
        self.inner = self.inner.search_top_k(k);
        self
    }

    /// Maximum distance for semantically relevant conclusions (0.0–1.0).
    pub fn search_max_distance(mut self, d: f64) -> Self {
        self.inner = self.inner.search_max_distance(d);
        self
    }

    /// Include the most frequent conclusions.
    pub fn include_most_frequent(mut self, v: bool) -> Self {
        self.inner = self.inner.include_most_frequent(v);
        self
    }

    /// Maximum number of conclusions to include (1–100).
    pub fn max_conclusions(mut self, m: u32) -> Self {
        self.inner = self.inner.max_conclusions(m);
        self
    }

    /// Execute the request and return the session context.
    pub fn send(self) -> Result<crate::types::session::SessionContext> {
        block_on(self.inner.send())
    }
}