objectiveai-sdk 2.1.0

ObjectiveAI SDK, definitions, and utilities
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
//! Viewer HTTP client. Fire-and-forget event publisher with exponential
//! backoff retries.
//!
//! The client owns an unbounded mpsc channel + a background tokio task.
//! Each `send_*` method is synchronous — it serializes the request and
//! pushes it onto the channel; the background task POSTs to the
//! viewer's HTTP endpoint with retry. Callers don't await network I/O.
//!
//! This module is intentionally ctx-free. Per-request `address` and
//! `signature` overrides are passed explicitly to each `send_*` call.
//! Higher-level consumers (e.g. `objectiveai-api`) can wrap this client
//! and do per-request context resolution on top.

use std::sync::Arc;
use std::time::Duration;

use tokio::sync::mpsc;

use super::request::{
    AgentCompletionCreateParams, AgentCompletionRequest,
    FunctionExecutionCreateParams, FunctionExecutionRequest,
    FunctionInventionRecursiveCreateParams, FunctionInventionRecursiveRequest,
    LaboratoryExecutionCreateParams, LaboratoryExecutionRequest, Request,
    ResponseError,
};

/// Resolved per-request override pair.
///
/// `None` on either field means "fall back to the [`Client`]'s
/// `default_*`".
#[derive(Debug, Clone)]
pub(super) struct ViewerData {
    pub address: Option<Arc<String>>,
    pub signature: Option<Arc<String>>,
}

/// The viewer HTTP client. Constructed once at process startup; all
/// `send_*` methods take `&self` so the client is shared across the
/// app via `Arc<Client>`.
pub struct Client {
    tx: mpsc::UnboundedSender<(ViewerData, Request)>,
    /// Background task handle. `flush(self)` drops `tx` and `.await`s
    /// this so every enqueued request lands (or exhausts its retry
    /// budget) before the consumer drops the runtime.
    handle: tokio::task::JoinHandle<()>,
    /// Fallback address used when a `send_*` call's `address` is
    /// `None`. Set from the constructor's `address` argument, or from
    /// `VIEWER_ADDRESS` if `address` is `None` and the `env` feature
    /// is enabled.
    pub default_address: Option<Arc<String>>,
    /// Fallback signature used when a `send_*` call's `signature` is
    /// `None`. Set from the constructor's `signature` argument, or
    /// from `VIEWER_SIGNATURE` if `signature` is `None` and the `env`
    /// feature is enabled.
    pub default_signature: Option<Arc<String>>,
}

impl Client {
    /// Construct a new client and spawn its background task.
    ///
    /// `address` / `signature` defaults: an explicit `Some(...)` wins.
    /// When `None`, and the `env` feature is enabled, falls back to
    /// the `VIEWER_ADDRESS` / `VIEWER_SIGNATURE` env vars. When both
    /// the argument and the env var are missing, the client has no
    /// default — every `send_*` call must supply its own `address`,
    /// or the request is dropped.
    ///
    /// Backoff parameters tune the [`backoff::ExponentialBackoff`]
    /// the background task uses for retry. `max_elapsed_time` caps
    /// how long the task keeps retrying a single failed request
    /// before giving up.
    pub fn new(
        http_client: reqwest::Client,
        address: Option<impl Into<String>>,
        signature: Option<impl Into<String>>,
        backoff_current_interval: Duration,
        backoff_initial_interval: Duration,
        backoff_randomization_factor: f64,
        backoff_multiplier: f64,
        backoff_max_interval: Duration,
        backoff_max_elapsed_time: Duration,
    ) -> Self {
        let default_address = match address {
            Some(s) => Some(Arc::new(s.into())),
            #[cfg(feature = "env")]
            None => std::env::var("VIEWER_ADDRESS").ok().map(Arc::new),
            #[cfg(not(feature = "env"))]
            None => None,
        };
        let default_signature = match signature {
            Some(s) => Some(Arc::new(s.into())),
            #[cfg(feature = "env")]
            None => std::env::var("VIEWER_SIGNATURE").ok().map(Arc::new),
            #[cfg(not(feature = "env"))]
            None => None,
        };

        let (tx, mut rx) = mpsc::unbounded_channel::<(ViewerData, Request)>();

        let bg_default_address = default_address.clone();
        let bg_default_signature = default_signature.clone();

        let handle = tokio::spawn(async move {
            while let Some((viewer_data, request)) = rx.recv().await {
                let (address, signature) = match viewer_data.address {
                    Some(addr) => (addr, viewer_data.signature),
                    None => match &bg_default_address {
                        Some(addr) => {
                            (addr.clone(), bg_default_signature.clone())
                        }
                        None => continue,
                    },
                };

                let url = match &request {
                    Request::AgentCompletion(_) => {
                        format!("{}/agent/completions", address)
                    }
                    Request::FunctionExecution(_) => {
                        format!("{}/functions/executions", address)
                    }
                    Request::FunctionInventionRecursive(_) => {
                        format!("{}/functions/inventions/recursive", address)
                    }
                    Request::LaboratoryExecution(_) => {
                        format!("{}/laboratories/executions", address)
                    }
                    Request::AgentsFavoritesChanged(_) => {
                        format!("{}/agents/favorites/changed", address)
                    }
                };

                let body = match serde_json::to_vec(&request) {
                    Ok(body) => body,
                    Err(_) => continue,
                };

                let _ = backoff::future::retry(
                    backoff::ExponentialBackoff {
                        current_interval: backoff_current_interval,
                        initial_interval: backoff_initial_interval,
                        randomization_factor: backoff_randomization_factor,
                        multiplier: backoff_multiplier,
                        max_interval: backoff_max_interval,
                        max_elapsed_time: Some(backoff_max_elapsed_time),
                        start_time: std::time::Instant::now(),
                        clock: backoff::SystemClock::default(),
                    },
                    || {
                        let http_client = &http_client;
                        let url = &url;
                        let body = &body;
                        let signature = &signature;
                        async move {
                            let mut req = http_client
                                .post(url.as_str())
                                .header("Content-Type", "application/json")
                                .body(body.clone());

                            if let Some(sig) = signature {
                                req = req
                                    .header("X-VIEWER-SIGNATURE", sig.as_str());
                            }

                            let response = req
                                .send()
                                .await
                                .map_err(backoff::Error::transient)?;

                            if response.status().is_success() {
                                Ok(())
                            } else {
                                Err(backoff::Error::transient(
                                    response.error_for_status().unwrap_err(),
                                ))
                            }
                        }
                    },
                )
                .await;
            }
        });

        Self {
            tx,
            handle,
            default_address,
            default_signature,
        }
    }

    /// Closes the channel and awaits the background task. After this
    /// returns, every enqueued request has either succeeded or
    /// exhausted its retry budget. Takes `self` so the
    /// can't-send-after-flush invariant is enforced by the type
    /// system.
    ///
    /// Intended for short-lived consumers (e.g. the cli) that must
    /// drain in-flight POSTs before dropping the tokio runtime. Long-
    /// lived consumers (api server) can rely on the natural drop
    /// behavior — when the `Client` drops, `tx` drops, the bg task's
    /// `rx.recv()` returns `None`, and the loop exits.
    pub async fn flush(self) {
        let Self { tx, handle, .. } = self;
        drop(tx);
        let _ = handle.await;
    }

    /// Internal helper. Pushes one `(ViewerData, Request)` onto the
    /// channel; the background task takes it from there.
    fn enqueue(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        request: Request,
    ) {
        let _ = self.tx.send((ViewerData { address, signature }, request));
    }

    pub fn send_agent_completion_begin(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        request: Arc<
            crate::agent::completions::request::AgentCompletionCreateParams,
        >,
    ) {
        self.enqueue(
            address,
            signature,
            Request::AgentCompletion(AgentCompletionRequest::Begin(
                AgentCompletionCreateParams { id, inner: request },
            )),
        );
    }

    pub fn send_agent_completion_continue(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        chunk: crate::agent::completions::response::streaming::AgentCompletionChunk,
    ) {
        self.enqueue(
            address,
            signature,
            Request::AgentCompletion(AgentCompletionRequest::Continue(chunk)),
        );
    }

    pub fn send_agent_completion_error(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        error: crate::error::ResponseError,
    ) {
        self.enqueue(
            address,
            signature,
            Request::AgentCompletion(AgentCompletionRequest::Error(
                ResponseError { id, inner: error },
            )),
        );
    }

    pub fn send_function_execution_begin(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        request: Arc<crate::functions::executions::request::FunctionExecutionCreateParams>,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionExecution(FunctionExecutionRequest::Begin(
                FunctionExecutionCreateParams { id, inner: request },
            )),
        );
    }

    pub fn send_function_execution_continue(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        chunk: crate::functions::executions::response::streaming::FunctionExecutionChunk,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionExecution(FunctionExecutionRequest::Continue(
                chunk,
            )),
        );
    }

    pub fn send_function_execution_error(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        error: crate::error::ResponseError,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionExecution(FunctionExecutionRequest::Error(
                ResponseError { id, inner: error },
            )),
        );
    }

    pub fn send_function_invention_recursive_begin(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        request: Arc<
            crate::functions::inventions::recursive::request::FunctionInventionRecursiveCreateParams,
        >,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionInventionRecursive(
                FunctionInventionRecursiveRequest::Begin(
                    FunctionInventionRecursiveCreateParams {
                        id,
                        inner: request,
                    },
                ),
            ),
        );
    }

    pub fn send_function_invention_recursive_continue(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        chunk: crate::functions::inventions::recursive::response::streaming::FunctionInventionRecursiveChunk,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionInventionRecursive(
                FunctionInventionRecursiveRequest::Continue(chunk),
            ),
        );
    }

    pub fn send_function_invention_recursive_error(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        error: crate::error::ResponseError,
    ) {
        self.enqueue(
            address,
            signature,
            Request::FunctionInventionRecursive(
                FunctionInventionRecursiveRequest::Error(ResponseError {
                    id,
                    inner: error,
                }),
            ),
        );
    }

    pub fn send_laboratory_execution_begin(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        request: Arc<crate::laboratories::executions::request::LaboratoryExecutionCreateParams>,
    ) {
        self.enqueue(
            address,
            signature,
            Request::LaboratoryExecution(LaboratoryExecutionRequest::Begin(
                LaboratoryExecutionCreateParams { id, inner: request },
            )),
        );
    }

    pub fn send_laboratory_execution_continue(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        chunk: crate::laboratories::executions::response::streaming::LaboratoryExecutionChunk,
    ) {
        self.enqueue(
            address,
            signature,
            Request::LaboratoryExecution(LaboratoryExecutionRequest::Continue(
                chunk,
            )),
        );
    }

    pub fn send_laboratory_execution_error(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        id: String,
        error: crate::error::ResponseError,
    ) {
        self.enqueue(
            address,
            signature,
            Request::LaboratoryExecution(LaboratoryExecutionRequest::Error(
                ResponseError { id, inner: error },
            )),
        );
    }

    /// Enqueue an `agents_favorites_changed` notification. Posts to
    /// `<address>/agents/favorites/changed`. Fired by the cli's
    /// `agents favorites config {add,del,edit}` handlers so any
    /// running viewer that exposes a `useFavoriteAgents()`-style hook
    /// can refresh its favorites list.
    pub fn send_agents_favorites_changed(
        &self,
        address: Option<Arc<String>>,
        signature: Option<Arc<String>>,
        notification: crate::agent::favorites::ChangedNotification,
    ) {
        self.enqueue(
            address,
            signature,
            Request::AgentsFavoritesChanged(notification),
        );
    }
}