objectiveai-cli 2.1.1

ObjectiveAI command-line interface and embeddable library
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
//! `LogWriter<C>` — postgres log writer fronted by an mpsc sender.
//!
//! Architecturally:
//!
//! - The constructor (`write_agent_completion` etc.) spawns a tokio
//!   task that owns the [`LogWriterState`] and the
//!   `mpsc::UnboundedReceiver<C>`. It returns the [`LogWriter`]
//!   handle plus a [`tokio::sync::oneshot::Receiver<String>`] that
//!   fires the first time the writer learns the stream's primary
//!   `response_id`.
//! - [`LogWriter::write`] is **synchronous** — it just hands the
//!   chunk to the listener task via `UnboundedSender::send`. The
//!   caller's chunk-yield hot path stays off the DB write critical
//!   path.
//! - The listener task drains every queued chunk per loop iteration
//!   and `.push()`-aggregates them into one before running the
//!   per-chunk persistence logic ([`LogWriterState::apply_chunk`]).
//!   Aggregation is correct because each tier's chunk is a cumulative
//!   roll-up of state — `push` folds the later chunk's deltas into
//!   the earlier one's accumulators (`AgentCompletionChunk::push` /
//!   `VectorCompletionChunk::push` / `FunctionExecutionChunk::push`).
//! - [`LogWriter::finalize`] consumes the writer by value, drops the
//!   sender, and `.await`s the JoinHandle. By the time it returns,
//!   both invariants hold: the channel is empty (sender dropped →
//!   `recv()` returned `None` only after every queued chunk was
//!   consumed) and the task's future has fully completed (no
//!   in-flight row-bucket joins or blob writes).
//!
//! Per-chunk persistence (unchanged from the prior in-line `write`):
//!
//! 1. **First chunk**: capture the chunk's `response_id`, INSERT the
//!    request blob (no `agent_instance_hierarchy` on the blob — that
//!    linkage lives in `logs.messages`).
//! 2. **Every chunk**: walk `chunk_rows(chunk)`, gate each yielded
//!    [`RowValue`] through the shadow (Skip path is pure-memory),
//!    bucket the survivors by `agent_instance_hierarchy`. For every
//!    agent the writer hasn't seen yet in this stream's lifetime,
//!    prepend a `logs.messages` row that registers the request blob
//!    in that agent's history.
//! 3. **Per-bucket execution**: rows within one agent's bucket fire
//!    sequentially (so the per-agent ORDER BY `"index"` matches the
//!    iterator's order). All buckets fire concurrently via
//!    `try_join_all`. The response blob update runs in parallel with
//!    the bucket fan-out via `tokio::join!`.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;

use objectiveai_sdk::agent::completions::request::AgentCompletionCreateParams;
use objectiveai_sdk::agent::completions::response::streaming::{
    AgentCompletionChunk, AgentCompletionIds,
};
use objectiveai_sdk::functions::executions::request::FunctionExecutionCreateParams;
use objectiveai_sdk::functions::executions::response::streaming::FunctionExecutionChunk;
use objectiveai_sdk::vector::completions::request::VectorCompletionCreateParams;
use objectiveai_sdk::vector::completions::response::streaming::VectorCompletionChunk;
use serde::Serialize;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::JoinHandle;

use crate::db::Pool;

use super::row::{RowValue, RowsIter};
use super::rows::{
    agent_completion_chunk_rows, function_execution_chunk_rows, vector_completion_chunk_rows,
};
use super::shadow::{Shadow, WriteOp};
use super::write::{
    Tier, insert_request_blob, insert_request_messages_row, insert_response_blob,
    update_response_blob, write_value,
};

pub trait WriterChunk {
    fn primary_id(&self) -> &str;
}

impl WriterChunk for AgentCompletionChunk {
    fn primary_id(&self) -> &str {
        self.id.as_str()
    }
}
impl WriterChunk for VectorCompletionChunk {
    fn primary_id(&self) -> &str {
        self.id.as_str()
    }
}
impl WriterChunk for FunctionExecutionChunk {
    fn primary_id(&self) -> &str {
        self.id.as_str()
    }
}

/// CLI-side wrapper exposing the SDK's intrinsic `push(&mut self,
/// other: &Self)` method via a uniform trait. Each impl simply
/// delegates to the chunk type's inherent method — the SDK already
/// guarantees `push` is a correct accumulator for the tier's
/// cumulative-state semantics.
pub trait ChunkPush {
    fn push(&mut self, other: &Self);
}

impl ChunkPush for AgentCompletionChunk {
    fn push(&mut self, other: &Self) {
        AgentCompletionChunk::push(self, other);
    }
}
impl ChunkPush for VectorCompletionChunk {
    fn push(&mut self, other: &Self) {
        VectorCompletionChunk::push(self, other);
    }
}
impl ChunkPush for FunctionExecutionChunk {
    fn push(&mut self, other: &Self) {
        FunctionExecutionChunk::push(self, other);
    }
}

/// Background-task-fronted log writer.
///
/// Construction (via `write_agent_completion` etc.) spawns a tokio
/// task that owns the per-stream [`LogWriterState`]. The handle here
/// is a thin sender + JoinHandle pair.
pub struct LogWriter<C> {
    tx: mpsc::UnboundedSender<C>,
    handle: JoinHandle<Result<(), crate::error::Error>>,
    /// Toggled `false` → `true` by the listener task once it has
    /// completed a single successful `apply_chunk`. Powers
    /// [`LogWriter::written_once`] (sync peek) and
    /// [`LogWriter::wait_written_once`] (async wait).
    written_rx: watch::Receiver<bool>,
    _chunk: PhantomData<fn() -> C>,
}

impl<C> LogWriter<C> {
    /// Hand off one chunk to the listener task. Returns
    /// `Err(Error::Instance(_))` only when the listener has already
    /// exited — typically because an earlier DB write failed. The
    /// caller should treat that error the same way it would treat an
    /// upstream stream error: stop reading, surface upward.
    pub fn write(&self, chunk: C) -> Result<(), crate::error::Error> {
        self.tx
            .send(chunk)
            .map_err(|_| crate::error::Error::Instance(
                "log writer task has exited (earlier write failed)".to_string(),
            ))
    }

    /// Sync peek: has the listener completed at least one successful
    /// `apply_chunk` batch? Flips `false → true` exactly once,
    /// immediately after the first batch's write completes and
    /// before the listener parks on the next `recv`.
    pub fn written_once(&self) -> bool {
        *self.written_rx.borrow()
    }

    /// Async wait that resolves once the listener has completed its
    /// first successful `apply_chunk` batch. Returns immediately if
    /// that already happened. Errors only if the listener task
    /// exited before its first successful write (DB error on the
    /// very first batch).
    pub async fn wait_written_once(&self) -> Result<(), crate::error::Error> {
        let mut rx = self.written_rx.clone();
        rx.wait_for(|b| *b)
            .await
            .map(|_| ())
            .map_err(|_| crate::error::Error::Instance(
                "log writer task exited before completing its first write".to_string(),
            ))
    }

    /// Consume the writer. Drops the sender (signaling EOF to the
    /// listener) and awaits the task. Returns only once:
    ///
    /// - the channel is empty: `recv()` returns `None` only after the
    ///   listener has drained every queued chunk, AND
    /// - no work is in flight: the task's future has fully completed,
    ///   so no row-bucket joins or blob writes remain pending.
    ///
    /// Surfaces the first DB error the task encountered, if any.
    pub async fn finalize(self) -> Result<(), crate::error::Error> {
        let LogWriter { tx, handle, .. } = self;
        drop(tx);
        match handle.await {
            Ok(inner) => inner,
            Err(e) => Err(crate::error::Error::Instance(
                format!("log writer task: {e}"),
            )),
        }
    }
}

/// All the per-stream state the listener task owns. Was previously
/// inlined onto `LogWriter`; now lives entirely inside the spawned
/// task so the handle stays send-and-clone-cheap.
struct LogWriterState<C> {
    pool: Pool,
    tier: Tier,
    request_body: serde_json::Value,
    /// AIH of the caller who issued the request that spawned this
    /// writer (pulled from `ctx.config.agent_instance_hierarchy` at
    /// `spawn_writer` time). Written into the request blob row at
    /// `insert_request_blob` time. Constant for the writer's
    /// lifetime — one request = one sender.
    sender_agent_instance_hierarchy: String,
    rows_fn: for<'a> fn(&'a C) -> RowsIter<'a>,
    primary_id: Option<String>,
    /// Per-streaming-content-row shadow. Skip path is allocation-free.
    shadow: Shadow,
    /// Last-written response blob bytes — `PartialEq` against the
    /// next tick's serialized chunk decides Insert / Update / Skip.
    last_response_blob: Option<Vec<u8>>,
    /// Once-flag for the request blob INSERT.
    request_written: bool,
    /// Every `agent_instance_hierarchy` we've observed in this
    /// stream's lifetime. The first time an agent appears in the row
    /// iterator we insert a `logs.messages` row registering the
    /// request blob in that agent's history; subsequent ticks see
    /// the agent already-marked and skip the registration.
    seen_agents: HashSet<String>,
    _chunk: PhantomData<fn() -> C>,
}

impl<C> LogWriterState<C> {
    fn new(
        pool: Pool,
        tier: Tier,
        request_body: serde_json::Value,
        sender_agent_instance_hierarchy: String,
        rows_fn: for<'a> fn(&'a C) -> RowsIter<'a>,
    ) -> Self {
        Self {
            pool,
            tier,
            request_body,
            sender_agent_instance_hierarchy,
            rows_fn,
            primary_id: None,
            shadow: Shadow::new(),
            last_response_blob: None,
            request_written: false,
            seen_agents: HashSet::new(),
            _chunk: PhantomData,
        }
    }

    async fn apply_chunk(&mut self, chunk: &C) -> Result<(), crate::error::Error>
    where
        C: WriterChunk + AgentCompletionIds + Serialize + Send + Sync,
    {
        // First chunk: stamp the primary id, write the request blob
        // ONCE. The request blob has no agent_instance_hierarchy.
        if self.primary_id.is_none() {
            self.primary_id = Some(chunk.primary_id().to_string());
        }
        let response_id = self.primary_id.clone().expect("set above");
        let created_at_seed = now_secs() as i64;

        if !self.request_written {
            let request_body = self.request_body.clone();
            insert_request_blob(
                &self.pool,
                self.tier,
                &response_id,
                &request_body,
                &self.sender_agent_instance_hierarchy,
                created_at_seed,
            )
            .await?;
            self.request_written = true;
        }

        // Walk rows, gate via shadow, bucket survivors by
        // agent_instance_hierarchy. Vec inside the HashMap preserves
        // iterator order so per-bucket sequential awaits match
        // chunk_rows()'s ordering.
        let mut buckets: HashMap<&str, Vec<(WriteOp, RowValue<'_>)>> = HashMap::new();
        for value in (self.rows_fn)(chunk) {
            let key = value.agent_instance_hierarchy();
            match self.shadow.record(&value) {
                WriteOp::Skip => continue,
                op => buckets.entry(key).or_default().push((op, value)),
            }
        }

        // Serialize the response chunk once, diff against the
        // last-written blob.
        let response_bytes = serde_json::to_vec(chunk)?;
        let blob_op = match &self.last_response_blob {
            Some(prev) if prev == &response_bytes => WriteOp::Skip,
            Some(_) => WriteOp::Update,
            None => WriteOp::Insert,
        };

        // Build the per-agent bucket futures. Each future runs its
        // rows sequentially (order matters within one agent's
        // history); different agents run concurrently via
        // `try_join_all`. The seen_agents mutation happens
        // synchronously inside the map closure — by the time the
        // futures actually run, every bucket already knows whether it
        // owes a request-messages row.
        let pool = &self.pool;
        let tier = self.tier;
        let resp_id = response_id.as_str();
        let seen_agents = &mut self.seen_agents;
        let bucket_futures: Vec<
            Pin<Box<dyn Future<Output = Result<(), crate::error::Error>> + Send + '_>>,
        > = buckets
            .into_iter()
            .map(|(hier, items)| {
                let needs_request_row = !seen_agents.contains(hier);
                if needs_request_row {
                    seen_agents.insert(hier.to_string());
                }
                Box::pin(async move {
                    if needs_request_row {
                        insert_request_messages_row(
                            pool,
                            tier,
                            resp_id,
                            hier,
                            created_at_seed,
                        )
                        .await?;
                    }
                    for (op, value) in &items {
                        write_value(pool, *op, value, created_at_seed).await?;
                    }
                    Ok::<(), crate::error::Error>(())
                })
                    as Pin<
                        Box<
                            dyn Future<Output = Result<(), crate::error::Error>>
                                + Send
                                + '_,
                        >,
                    >
            })
            .collect();

        let content_fut = futures::future::try_join_all(bucket_futures);
        let blob_fut = async {
            match blob_op {
                WriteOp::Insert => {
                    insert_response_blob(
                        pool,
                        tier,
                        resp_id,
                        chunk,
                        created_at_seed,
                    )
                    .await
                }
                WriteOp::Update => {
                    update_response_blob(pool, tier, resp_id, chunk, created_at_seed).await
                }
                WriteOp::Skip => Ok(()),
            }
        };
        let (content_res, blob_res) = tokio::join!(content_fut, blob_fut);
        content_res?;
        blob_res?;

        if blob_op != WriteOp::Skip {
            self.last_response_blob = Some(response_bytes);
        }

        Ok(())
    }
}

/// Listener loop. One iteration:
///
/// 1. Block on `rx.recv()` for the first chunk of a batch.
/// 2. Drain any other chunks queued behind it via `try_recv`,
///    `.push()`-aggregating them into the first.
/// 3. Apply the aggregated chunk to the state.
/// 4. If this was the first successful batch, flip `written_tx` to
///    `true` (powers `LogWriter::wait_written_once`).
/// 5. If `primary_id` just became known, fire the ready oneshot.
///
/// On `recv() = None` (sender dropped via `finalize`), the loop
/// exits cleanly. On any DB error from `apply_chunk`, the loop
/// exits with `Err`; subsequent sender sends fail with `SendError`,
/// which `LogWriter::write` maps to a stable `Error::Instance`.
async fn listener_loop<C>(
    mut rx: mpsc::UnboundedReceiver<C>,
    mut state: LogWriterState<C>,
    ready_tx: oneshot::Sender<String>,
    written_tx: watch::Sender<bool>,
) -> Result<(), crate::error::Error>
where
    C: WriterChunk + AgentCompletionIds + ChunkPush + Serialize + Send + Sync,
{
    let mut ready_tx = Some(ready_tx);
    let mut written_fired = false;
    while let Some(first) = rx.recv().await {
        // Coalesce: aggregate any queued chunks into the first.
        let mut agg = first;
        while let Ok(next) = rx.try_recv() {
            agg.push(&next);
        }
        state.apply_chunk(&agg).await?;
        // First successful apply: flip the watch true exactly once.
        // Subsequent batches don't touch it (the value is already
        // true; no point waking waiters again).
        if !written_fired {
            let _ = written_tx.send(true);
            written_fired = true;
        }
        // Fire the oneshot the first time primary_id becomes known.
        // `apply_chunk` sets `primary_id` on the first invocation, so
        // by the time we get here it's already Some on at least the
        // first iteration.
        if let Some(tx) = ready_tx.take() {
            match state.primary_id.as_deref() {
                Some(id) => {
                    let _ = tx.send(id.to_string());
                }
                None => {
                    ready_tx = Some(tx);
                }
            }
        }
    }
    // EOF: nothing to flush — the in-flight write completed before
    // recv() returned None.
    Ok(())
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn spawn_writer<C>(
    pool: Pool,
    tier: Tier,
    request_body: serde_json::Value,
    sender_agent_instance_hierarchy: String,
    rows_fn: for<'a> fn(&'a C) -> RowsIter<'a>,
) -> (LogWriter<C>, oneshot::Receiver<String>)
where
    C: WriterChunk + AgentCompletionIds + ChunkPush + Serialize + Send + Sync + 'static,
{
    let (tx, rx) = mpsc::unbounded_channel();
    let (ready_tx, ready_rx) = oneshot::channel();
    let (written_tx, written_rx) = watch::channel(false);
    let state = LogWriterState::new(
        pool,
        tier,
        request_body,
        sender_agent_instance_hierarchy,
        rows_fn,
    );
    let handle = tokio::spawn(listener_loop(rx, state, ready_tx, written_tx));
    (
        LogWriter {
            tx,
            handle,
            written_rx,
            _chunk: PhantomData,
        },
        ready_rx,
    )
}

pub fn write_agent_completion(
    pool: &Pool,
    params: &AgentCompletionCreateParams,
    sender_agent_instance_hierarchy: String,
) -> Result<
    (LogWriter<AgentCompletionChunk>, oneshot::Receiver<String>),
    crate::error::Error,
> {
    let body = serde_json::to_value(params)?;
    Ok(spawn_writer(
        pool.clone(),
        Tier::Agent,
        body,
        sender_agent_instance_hierarchy,
        agent_completion_chunk_rows,
    ))
}

pub fn write_vector_completion(
    pool: &Pool,
    params: &VectorCompletionCreateParams,
    sender_agent_instance_hierarchy: String,
) -> Result<
    (LogWriter<VectorCompletionChunk>, oneshot::Receiver<String>),
    crate::error::Error,
> {
    let body = serde_json::to_value(params)?;
    Ok(spawn_writer(
        pool.clone(),
        Tier::Vector,
        body,
        sender_agent_instance_hierarchy,
        vector_completion_chunk_rows,
    ))
}

pub fn write_function_execution(
    pool: &Pool,
    params: &FunctionExecutionCreateParams,
    sender_agent_instance_hierarchy: String,
) -> Result<
    (LogWriter<FunctionExecutionChunk>, oneshot::Receiver<String>),
    crate::error::Error,
> {
    let body = serde_json::to_value(params)?;
    Ok(spawn_writer(
        pool.clone(),
        Tier::Function,
        body,
        sender_agent_instance_hierarchy,
        function_execution_chunk_rows,
    ))
}