Skip to main content

objectiveai_cli/command/agents/queue/
list.rs

1//! `agents queue read pending` — stream every pending queue row
2//! for the resolved targets, parts-grouped. Symmetric with
3//! `agents logs read all`'s handler: `Vec<Target>` loop, per-target
4//! resolution, `FuturesUnordered` fan-out.
5
6use std::pin::Pin;
7
8use futures::Stream;
9use futures::StreamExt;
10use futures::stream::FuturesUnordered;
11use objectiveai_sdk::cli::command::agents::queue::list::{
12    Request, ResponseItem, Target,
13};
14
15use crate::context::Context;
16use crate::db::message_queue::ResolvedTarget;
17use crate::db::tags;
18use crate::error::Error;
19
20type ItemStream = Pin<Box<dyn Stream<Item = Result<ResponseItem, Error>> + Send>>;
21
22pub async fn execute(ctx: &Context, request: Request) -> Result<ItemStream, Error> {
23    let default_parent = ctx.config.agent_instance_hierarchy.clone();
24    let db = ctx.db_client().await?.clone();
25    let after_id = request.after_id;
26    let limit = request.limit;
27    let stream = async_stream::stream! {
28        let mut inflight = FuturesUnordered::new();
29        for target in request.targets {
30            let db = db.clone();
31            let default_parent = default_parent.clone();
32            inflight.push(async move {
33                let resolved = resolve_target(&db, target, &default_parent).await?;
34                let items = crate::db::message_queue::list_pending_for_targets(
35                    &db, std::slice::from_ref(&resolved), after_id, limit,
36                ).await.map_err(Error::from)?;
37                Ok::<Vec<ResponseItem>, Error>(items)
38            });
39        }
40        while let Some(result) = inflight.next().await {
41            match result {
42                Ok(items) => {
43                    for item in items {
44                        yield Ok(item);
45                    }
46                }
47                Err(e) => yield Err(e),
48            }
49        }
50    };
51    Ok(Box::pin(stream))
52}
53
54/// Direct mode resolves to an AIH; tag mode resolves the tag via
55/// `tags::lookup` to the tag NAME for any registered tag (BOUND or
56/// GROUPED) — the queue is keyed by tag name, so it's readable even
57/// before the agent is spawned. Only an unregistered (ABSENT) tag
58/// errors. (Unlike `agents logs read all`, which needs the agent
59/// spawned because logs don't exist until then.)
60async fn resolve_target(
61    db: &crate::db::Pool,
62    target: Target,
63    default_parent: &str,
64) -> Result<ResolvedTarget, Error> {
65    match target {
66        Target::Direct {
67            parent_agent_instance_hierarchy,
68            agent_instance,
69        } => {
70            let parent =
71                parent_agent_instance_hierarchy.unwrap_or_else(|| default_parent.to_string());
72            Ok(ResolvedTarget::Hierarchy(format!("{parent}/{agent_instance}")))
73        }
74        // The caller's own AIH itself — no child leaf appended.
75        Target::Me => Ok(ResolvedTarget::Hierarchy(default_parent.to_string())),
76        // A registered tag's queue is keyed by the tag NAME — queue rows
77        // carry the literal tag, not the resolved hierarchy. So the queue
78        // doesn't depend on the agent being spawned: a GROUPED (registered
79        // but not-yet-spawned) tag has a perfectly readable queue, and a
80        // rebind doesn't strand queued prompts. Both BOUND and GROUPED
81        // therefore resolve to the tag name; only an unregistered (ABSENT)
82        // tag has no queue.
83        Target::Tag { agent_tag } => match tags::lookup(db, &agent_tag).await? {
84            tags::LookupState::Bound { .. } | tags::LookupState::Grouped { .. } => {
85                Ok(ResolvedTarget::Tag(agent_tag))
86            }
87            tags::LookupState::Absent => Err(Error::TagNotFound(agent_tag)),
88        },
89    }
90}
91
92pub mod request_schema {
93    use objectiveai_sdk::cli::command::agents::queue::list as sdk;
94    use objectiveai_sdk::cli::command::agents::queue::list::request_schema::{
95        Request, Response,
96    };
97
98    use crate::context::Context;
99    use crate::error::Error;
100
101    pub async fn execute(_ctx: &Context, _request: Request) -> Result<Response, Error> {
102        Ok(objectiveai_sdk::cli::command::ResponseSchema(
103            schemars::schema_for!(sdk::Request),
104        ))
105    }
106}
107
108pub mod response_schema {
109    use objectiveai_sdk::cli::command::agents::queue::list as sdk;
110    use objectiveai_sdk::cli::command::agents::queue::list::response_schema::{
111        Request, Response,
112    };
113
114    use crate::context::Context;
115    use crate::error::Error;
116
117    pub async fn execute(_ctx: &Context, _request: Request) -> Result<Response, Error> {
118        Ok(objectiveai_sdk::cli::command::ResponseSchema(
119            schemars::schema_for!(sdk::ResponseItem),
120        ))
121    }
122}