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
//! `agents message` — stream-aware delivery primitive.
//!
//! See the SDK's `agents::message` module doc for the
//! external semantics. The cli-side decision tree:
//!
//! 1. **Resolve target.** Direct → compose `{parent}/{instance}`.
//!    Tag → look up in `tags`; BOUND falls through as a Direct
//!    equivalent, PENDING/ABSENT falls back to pure enqueue
//!    against the tag (or errors when message is `None`).
//! 2. **Resolve content.** `Some(rm)` → `resolve_message` →
//!    `RichContent`. `None` → tracked through the rest of the
//!    flow; the eventual spawn (if any) gets an empty `messages`
//!    vec.
//! 3. **Branch on `dangerous_advanced.stream`:**
//!    - `stream=true` → `execute_streaming`.
//!    - `stream=false | None` → `execute_unary`.

use std::path::PathBuf;
use std::pin::Pin;

use futures::{Stream, StreamExt};
use objectiveai_sdk::agent::completions::message::{Message, RichContent, UserMessage};
use objectiveai_sdk::agent::completions::request::AgentCompletionCreateParams;
use objectiveai_sdk::cli::command::agents::message::{
    EnqueueMode, MessageTarget, Request, RequestDangerousAdvanced, RequestMessage, ResponseItem,
};
use objectiveai_sdk::cli::command::agents::spawn::ResponseItem as SpawnResponseItem;
use objectiveai_sdk::cli::command::{BinaryExecutor, CommandExecutor};

use crate::context::Context;
use crate::db::tags::LookupState;
use crate::error::Error;
use crate::lock_file;

type ItemStream = Pin<Box<dyn Stream<Item = Result<ResponseItem, Error>> + Send>>;

pub async fn execute(ctx: &Context, request: Request) -> Result<ItemStream, Error> {
    // Fire-and-forget short-circuit. `--enqueue` /
    // `--enqueue-with-key` skip every interactive step (no
    // `tags::lookup`, no lock-file race, no spawn-takeover, no
    // detached respawn) and just persist into `message_queue`.
    if let Some(mode) = request.enqueue {
        return execute_enqueue(ctx, request.target, request.message, mode).await;
    }
    let want_stream = request
        .dangerous_advanced
        .as_ref()
        .and_then(|a| a.stream)
        .unwrap_or(false);
    let agents_dir = ctx
        .filesystem
        .base_dir()
        .join("instances")
        .join("agents");

    // Phase 1: resolve target → (hierarchy, tag) or early-return.
    let (hierarchy, _tag) = match resolve_target(ctx, &request).await? {
        ResolvedTarget::Hierarchy { hierarchy, tag } => (hierarchy, tag),
        ResolvedTarget::EnqueueAgainstTag { id, agent_tag } => {
            return Ok(once_item(ResponseItem::Enqueued {
                id,
                agent_instance_hierarchy: None,
                agent_tag: Some(agent_tag),
            }));
        }
    };

    // Phase 2: resolve the user payload — always required.
    let message_content = resolve_message(request.message.clone())?;

    if want_stream {
        let seed = request.dangerous_advanced.as_ref().and_then(|a| a.seed);
        execute_streaming(ctx, hierarchy, message_content, agents_dir, seed).await
    } else {
        execute_unary(ctx, hierarchy, message_content, agents_dir, request).await
    }
}

enum ResolvedTarget {
    /// Successfully resolved to a concrete hierarchy (Direct or
    /// BOUND tag). Caller continues into the lock-race flow.
    Hierarchy {
        hierarchy: String,
        #[allow(dead_code)] // exposed for future tag-binding hooks.
        tag: Option<String>,
    },
    /// Tag was unresolvable (PENDING / ABSENT). The message was
    /// already enqueued against the tag name; caller short-circuits
    /// with the assigned queue row id.
    EnqueueAgainstTag { id: i64, agent_tag: String },
}

async fn resolve_target(ctx: &Context, request: &Request) -> Result<ResolvedTarget, Error> {
    match &request.target {
        MessageTarget::Direct {
            parent_agent_instance_hierarchy,
            agent_instance,
        } => {
            let parent = parent_agent_instance_hierarchy
                .as_deref()
                .unwrap_or(&ctx.config.agent_instance_hierarchy);
            Ok(ResolvedTarget::Hierarchy {
                hierarchy: format!("{parent}/{agent_instance}"),
                tag: None,
            })
        }
        MessageTarget::Tag { agent_tag } => {
            let state = crate::db::tags::lookup(&ctx.db, agent_tag).await?;
            match state {
                LookupState::Bound {
                    agent_instance_hierarchy,
                } => Ok(ResolvedTarget::Hierarchy {
                    hierarchy: agent_instance_hierarchy,
                    tag: Some(agent_tag.clone()),
                }),
                LookupState::Grouped { .. } | LookupState::Absent => {
                    // No live target. Pure enqueue against the
                    // tag name — the queue reader resolves it later.
                    let content = resolve_message(request.message.clone())?;
                    let id = crate::db::message_queue::enqueue_with_content(
                        &ctx.db,
                        None,
                        Some(agent_tag.clone()),
                        &ctx.config.agent_instance_hierarchy,
                        None,
                        content,
                    )
                    .await?;
                    Ok(ResolvedTarget::EnqueueAgainstTag {
                        id,
                        agent_tag: agent_tag.clone(),
                    })
                }
            }
        }
    }
}

/// `stream=true`: try to acquire the lock immediately. If we get
/// it, skip enqueue + run spawn in-process. If we don't, enqueue +
/// race DB-delivery against blocking lock acquisition.
async fn execute_streaming(
    ctx: &Context,
    hierarchy: String,
    message_content: RichContent,
    agents_dir: PathBuf,
    seed: Option<i64>,
) -> Result<ItemStream, Error> {
    std::fs::create_dir_all(&agents_dir)
        .map_err(|e| Error::Instance(format!("create agents_dir: {e}")))?;
    let lock_path = agents_dir.join(hierarchy.replace('/', "_"));

    // Fast path: nobody holds the lock — we win it now.
    if let Some(claim) = lock_file::try_acquire(&lock_path) {
        return Ok(run_spawn_with(ctx, claim, hierarchy, message_content, seed).await?);
    }

    // Slow path: live owner. Enqueue + race.
    let queue_id = crate::db::message_queue::enqueue_with_content(
        &ctx.db,
        Some(hierarchy.clone()),
        None,
        &ctx.config.agent_instance_hierarchy,
        None,
        message_content.clone(),
    )
    .await?;

    let pool = ctx.db.clone();
    let lock_path_clone = lock_path.clone();
    tokio::select! {
        delivery = crate::db::message_queue::subscribe_delivered(&pool, queue_id) => {
            delivery?;
            Ok(once_item(ResponseItem::Delivered))
        }
        claim = lock_file::wait_acquire(&lock_path_clone) => {
            let claim = claim.map_err(|e| Error::Instance(format!(
                "lock acquisition: {e}"
            )))?;
            // We're the new owner. Reclaim our queue row before
            // spawning — the conduit shouldn't see it again.
            let _ = crate::db::message_queue::delete_by_id(
                &ctx.db,
                queue_id,
                &ctx.config.agent_instance_hierarchy,
            )
            .await;
            run_spawn_with(ctx, claim, hierarchy, message_content, seed).await
        }
    }
}

/// Drive `spawn::run_multi_pass` for this hierarchy. Pulls the
/// agent definition + latest continuation out of the logs DB
/// (single round-trip), pre-builds an
/// `AgentCompletionCreateParams` with the continuation stamped,
/// and threads the held `LockClaim` through the returned stream's
/// state so the lock is owned for the full spawn lifetime.
async fn run_spawn_with(
    ctx: &Context,
    claim: lock_file::LockClaim,
    hierarchy: String,
    message_content: RichContent,
    seed: Option<i64>,
) -> Result<ItemStream, Error> {
    let lookup = crate::db::logs::lookup_session(&ctx.db, &hierarchy)
        .await?
        .ok_or_else(|| {
            Error::Instance(format!("no prior session for {hierarchy:?}"))
        })?;

    let messages = vec![Message::User(UserMessage {
        content: message_content,
        name: None,
    })];
    let params = AgentCompletionCreateParams {
        messages,
        provider: None,
        agent: lookup.agent,
        response_format: None,
        seed,
        stream: Some(true),
        continuation: lookup.continuation,
    };
    let agents_dir = ctx
        .filesystem
        .base_dir()
        .join("instances")
        .join("agents");

    let inner = crate::command::agents::spawn::run_multi_pass(
        ctx.clone(),
        params,
        None,
        agents_dir,
    );

    // Tie `claim` into the stream's lifetime — drop = release
    // happens only when the consumer drops our output stream.
    let stream = async_stream::try_stream! {
        let _claim = claim;
        let mut inner = Box::pin(inner);
        while let Some(item) = inner.next().await {
            let ev = item?;
            match ev {
                SpawnResponseItem::Id(id) => {
                    yield ResponseItem::Id {
                        agent_instance_hierarchy: id,
                    }
                }
                SpawnResponseItem::Chunk(c) => yield ResponseItem::Chunk(c),
            }
        }
    };
    Ok(Box::pin(stream))
}

/// `stream=false`: check the lock. If held → enqueue + race
/// DB-delivery against lock-release; on release, delete the queue
/// row and re-check. If not held → re-exec ourselves as a detached
/// subprocess with `stream=true`, take the child's first item.
async fn execute_unary(
    ctx: &Context,
    hierarchy: String,
    message_content: RichContent,
    agents_dir: PathBuf,
    request: Request,
) -> Result<ItemStream, Error> {
    std::fs::create_dir_all(&agents_dir)
        .map_err(|e| Error::Instance(format!("create agents_dir: {e}")))?;
    let lock_path = agents_dir.join(hierarchy.replace('/', "_"));

    loop {
        if lock_file::is_held(&lock_path) {
            // Live agent — enqueue + race delivery vs release.
            let queue_id = crate::db::message_queue::enqueue_with_content(
                &ctx.db,
                Some(hierarchy.clone()),
                None,
                &ctx.config.agent_instance_hierarchy,
                None,
                message_content.clone(),
            )
            .await?;

            let pool = ctx.db.clone();
            let lock_path_clone = lock_path.clone();
            let race_outcome = tokio::select! {
                delivery = crate::db::message_queue::subscribe_delivered(&pool, queue_id) => {
                    delivery?;
                    RaceOutcome::Delivered
                }
                release = lock_file::wait_release(&lock_path_clone) => {
                    release.map_err(|e| Error::Instance(format!(
                        "lock release wait: {e}"
                    )))?;
                    RaceOutcome::Released
                }
            };
            match race_outcome {
                RaceOutcome::Delivered => {
                    return Ok(once_item(ResponseItem::Delivered));
                }
                RaceOutcome::Released => {
                    // Lock dropped — delete the queue row and
                    // loop back to re-check (a new live agent may
                    // have claimed it already, or no one will and
                    // we'll fall through to the detached respawn).
                    let _ = crate::db::message_queue::delete_by_id(
                &ctx.db,
                queue_id,
                &ctx.config.agent_instance_hierarchy,
            )
            .await;
                    continue;
                }
            }
        }

        // No live agent — re-exec the cli as a detached subprocess
        // running this same command with stream=true. The child
        // will acquire the lock and drive `spawn::run_multi_pass`.
        return execute_unary_respawn(&hierarchy, &request).await;
    }
}

enum RaceOutcome {
    Delivered,
    Released,
}

async fn execute_unary_respawn(
    hierarchy: &str,
    original: &Request,
) -> Result<ItemStream, Error> {
    // Convert Tag → Direct (the subprocess sees the resolved
    // hierarchy, not the original tag).
    let (parent, leaf) = match hierarchy.rsplit_once('/') {
        Some((p, l)) => (p.to_string(), l.to_string()),
        None => (String::new(), hierarchy.to_string()),
    };
    let mut child_request = original.clone();
    child_request.target = MessageTarget::Direct {
        parent_agent_instance_hierarchy: Some(parent),
        agent_instance: leaf,
    };
    match child_request.dangerous_advanced.as_mut() {
        Some(adv) => adv.stream = Some(true),
        None => {
            child_request.dangerous_advanced = Some(RequestDangerousAdvanced {
                stream: Some(true),
                ..Default::default()
            })
        }
    }

    let exe = std::env::current_exe()
        .map_err(|e| Error::Spawn("current_exe".into(), e))?;
    let executor = BinaryExecutor::from_path(exe).detach(true);
    let mut stream = executor
        .execute::<Request, ResponseItem>(child_request, None)
        .await
        .map_err(|e| Error::Instance(format!(
            "self-respawn for agents message: {e}"
        )))?;
    let first = stream
        .next()
        .await
        .ok_or(Error::EmptyStream)?
        .map_err(|e| Error::Instance(format!(
            "self-respawn for agents message: {e}"
        )))?;
    Ok(once_item(first))
}

fn once_item(item: ResponseItem) -> ItemStream {
    Box::pin(futures::stream::once(async move {
        Ok::<ResponseItem, Error>(item)
    }))
}

/// `--enqueue` / `--enqueue-with-key` handler. Bypasses every
/// delivery-side concern (tag resolution, lock-file race, spawn
/// takeover, detached respawn) and writes one row into
/// `message_queue` against the target. `Keyed` mode threads the key
/// through; `db::message_queue::enqueue_with_content` deletes any
/// prior row scoped to the same (target, key) pair before insert,
/// so re-issuing with the same key reliably replaces the prior
/// payload.
async fn execute_enqueue(
    ctx: &Context,
    target: MessageTarget,
    message: RequestMessage,
    mode: EnqueueMode,
) -> Result<ItemStream, Error> {
    let content = resolve_message(message)?;
    let key = match mode {
        EnqueueMode::Plain => None,
        EnqueueMode::Keyed { key } => Some(key),
    };
    let (hier, tag) = match target {
        MessageTarget::Direct {
            parent_agent_instance_hierarchy,
            agent_instance,
        } => {
            let parent = parent_agent_instance_hierarchy
                .as_deref()
                .unwrap_or(&ctx.config.agent_instance_hierarchy);
            (Some(format!("{parent}/{agent_instance}")), None)
        }
        MessageTarget::Tag { agent_tag } => (None, Some(agent_tag)),
    };
    let id = crate::db::message_queue::enqueue_with_content(
        &ctx.db,
        hier.clone(),
        tag.clone(),
        &ctx.config.agent_instance_hierarchy,
        key,
        content,
    )
    .await?;
    Ok(once_item(ResponseItem::Enqueued {
        id,
        agent_instance_hierarchy: hier,
        agent_tag: tag,
    }))
}

pub fn resolve_message(message: RequestMessage) -> Result<RichContent, Error> {
    let (simple, inline, file, python_inline, python_file) = match message {
        RequestMessage::Inline(rich) => return Ok(rich),
        RequestMessage::Simple(s) => (Some(s), None, None, None, None),
        RequestMessage::File(p) => (None, None, Some(p), None, None),
        RequestMessage::PythonInline(code) => (None, None, None, Some(code), None),
        RequestMessage::PythonFile(p) => (None, None, None, None, Some(p)),
    };
    crate::source_resolver::resolve_source(
        simple,
        inline,
        file,
        python_inline,
        python_file,
        RichContent::Text,
    )
}

pub mod request_schema {
    use objectiveai_sdk::cli::command::agents::message as sdk;
    use objectiveai_sdk::cli::command::agents::message::request_schema::{Request, Response};

    use crate::context::Context;
    use crate::error::Error;

    pub async fn execute(_ctx: &Context, _request: Request) -> Result<Response, Error> {
        Ok(objectiveai_sdk::cli::command::ResponseSchema(schemars::schema_for!(sdk::Request)))
    }
}

pub mod response_schema {
    use objectiveai_sdk::cli::command::agents::message as sdk;
    use objectiveai_sdk::cli::command::agents::message::response_schema::{Request, Response};

    use crate::context::Context;
    use crate::error::Error;

    pub async fn execute(_ctx: &Context, _request: Request) -> Result<Response, Error> {
        Ok(objectiveai_sdk::cli::command::ResponseSchema(schemars::schema_for!(sdk::Response)))
    }
}