Skip to main content

objectiveai_sdk/cli/command/agents/message/
mod.rs

1//! `agents message` — unary delivery primitive with a total FIFO
2//! order.
3//!
4//! Addresses an agent with the same shape as `agents spawn` (ref /
5//! tag / instance). A plain ref execs a detached `agents spawn`
6//! child carrying the message inline and returns the child's first
7//! item (`Id`). An instance or tag ALWAYS enqueues first — the queue
8//! row's id fixes the delivery position at commit time — then races
9//! the agent's lock; winning it execs a WAKE-UP spawn child (EMPTY
10//! message, the lock TRANSFERRED into it) that drains the queue
11//! oldest-id-first. Either way the call resolves `Delivered` when
12//! its own row is consumed, so delivery order is always enqueue
13//! order. For fire-and-forget parking without the race, see
14//! `agents enqueue`.
15
16use crate::agent::completions::message::RichContent;
17use crate::cli::command::CommandRequest;
18use crate::cli::command::agents::selector::AgentSelector;
19
20#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
21#[schemars(rename = "cli.command.agents.message.Request")]
22pub struct Request {
23    pub path_type: Path,
24    /// Who receives the message — same shape as `agents spawn`'s
25    /// `agent`: a direct ref spawns a fresh agent carrying this
26    /// message; a tag resolves at call time (BOUND → its live
27    /// hierarchy, GROUPED → first message spawns the agent and
28    /// upgrades the group, ABSENT → error); an instance targets an
29    /// existing hierarchy.
30    pub agent: AgentSelector,
31    /// Required payload. The eventual enqueue / delivery / spawn
32    /// always carries this exact `RichContent` as its single
33    /// user message.
34    pub message: RequestMessage,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    #[schemars(extend("omitempty" = true))]
37    pub dangerous_advanced: Option<RequestDangerousAdvanced>,
38    #[serde(flatten)]
39    pub base: crate::cli::command::RequestBase,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
43#[schemars(rename = "cli.command.agents.message.Path")]
44pub enum Path {
45    #[serde(rename = "agents/message")]
46    AgentsMessage,
47}
48
49#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
50#[schemars(rename = "cli.command.agents.message.RequestMessage")]
51pub enum RequestMessage {
52    #[schemars(title = "Inline")]
53    Inline(RichContent),
54    #[schemars(title = "Simple")]
55    Simple(String),
56    #[schemars(title = "File")]
57    File(std::path::PathBuf),
58    #[schemars(title = "PythonInline")]
59    PythonInline(String),
60    #[schemars(title = "PythonFile")]
61    PythonFile(std::path::PathBuf),
62}
63
64impl RequestMessage {
65    /// Append the flag pair (`--simple <s>` / `--inline <json>` /
66    /// `--file <path>` / `--python-inline <code>` /
67    /// `--python-file <path>`) for this variant to `out`. Used by
68    /// both this leaf's [`CommandRequest::into_command`] and by
69    /// `agents queue add`'s — same wire shape, same five flags.
70    pub fn push_flags(&self, out: &mut Vec<String>) {
71        match self {
72            RequestMessage::Inline(rich) => {
73                out.push("--inline".to_string());
74                out.push(
75                    serde_json::to_string(rich)
76                        .expect("RichContent serializes to JSON cleanly"),
77                );
78            }
79            RequestMessage::Simple(s) => {
80                out.push("--simple".to_string());
81                out.push(s.clone());
82            }
83            RequestMessage::File(p) => {
84                out.push("--file".to_string());
85                out.push(p.to_string_lossy().into_owned());
86            }
87            RequestMessage::PythonInline(code) => {
88                out.push("--python-inline".to_string());
89                out.push(code.clone());
90            }
91            RequestMessage::PythonFile(p) => {
92                out.push("--python-file".to_string());
93                out.push(p.to_string_lossy().into_owned());
94            }
95        }
96    }
97}
98
99#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
100#[schemars(rename = "cli.command.agents.message.RequestDangerousAdvanced")]
101pub struct RequestDangerousAdvanced {
102    /// Deterministic seed for the upstream model's RNG. Forwarded
103    /// onto the spawn child's `AgentCompletionCreateParams.seed`.
104    /// `None` here ⇒ the api picks; tests should always pin a
105    /// value to keep continuation turns reproducible.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    #[schemars(extend("omitempty" = true))]
108    pub seed: Option<i64>,
109}
110
111impl CommandRequest for Request {
112    fn request_base(&self) -> &crate::cli::command::RequestBase {
113        &self.base
114    }
115
116    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
117        Some(&mut self.base)
118    }
119}
120
121/// Unary response. Exactly one of these per call. Internally tagged
122/// via `type`; bare unit variant `Delivered` serializes as
123/// `{"type":"delivered"}`.
124#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
125#[serde(tag = "type", rename_all = "snake_case")]
126#[schemars(rename = "cli.command.agents.message.Response")]
127pub enum Response {
128    /// The queue row reached a live agent (its row flipped to
129    /// inactive — the API stamped its id onto an assistant chunk's
130    /// `request_message_ids`). The only resolution for instance and
131    /// tag targets: whether the handler found the agent live or
132    /// spawned it, the message rides the queue and this fires when
133    /// its own row is consumed.
134    #[schemars(title = "Delivered")]
135    Delivered,
136    /// Plain-ref targets only: the handler execed a detached
137    /// `agents spawn` child carrying the message inline and the
138    /// child yielded its `Id` first item — the bare
139    /// `agent_instance_hierarchy` the runner just minted.
140    #[schemars(title = "Id")]
141    Id { agent_instance_hierarchy: String },
142}
143
144#[derive(clap::Args)]
145pub struct Args {
146    #[command(flatten)]
147    pub agent: crate::cli::command::agents::selector::AgentSelectorArgs,
148    #[command(flatten)]
149    pub message: MessageArgs,
150    /// Raw JSON for [`RequestDangerousAdvanced`] (e.g.
151    /// `{"seed":42}`).
152    #[arg(long)]
153    pub dangerous_advanced: Option<String>,
154    #[command(flatten)]
155    pub base: crate::cli::command::RequestBaseArgs,
156}
157
158#[derive(clap::Args)]
159#[group(required = true, multiple = false)]
160pub struct MessageArgs {
161    /// Plain text — becomes one user message.
162    #[arg(long)]
163    pub simple: Option<String>,
164    /// Inline JSON `RichContent`.
165    #[arg(long)]
166    pub inline: Option<String>,
167    /// Path to a JSON file containing the rich content.
168    #[arg(long)]
169    pub file: Option<std::path::PathBuf>,
170    /// Inline Python code that produces the rich content.
171    #[arg(long)]
172    pub python_inline: Option<String>,
173    /// Path to a Python file that produces the rich content.
174    #[arg(long)]
175    pub python_file: Option<std::path::PathBuf>,
176}
177
178#[derive(clap::Args)]
179#[command(args_conflicts_with_subcommands = true)]
180pub struct Command {
181    #[command(flatten)]
182    pub args: Args,
183    #[command(subcommand)]
184    pub schema: Option<Schema>,
185}
186
187#[derive(clap::Subcommand)]
188pub enum Schema {
189    /// Emit the JSON Schema for this leaf's `Request` type and exit.
190    RequestSchema(request_schema::Args),
191    /// Emit the JSON Schema for this leaf's `Response` type and exit.
192    ResponseSchema(response_schema::Args),
193}
194
195impl TryFrom<Args> for Request {
196    type Error = crate::cli::command::FromArgsError;
197    fn try_from(args: Args) -> Result<Self, Self::Error> {
198        let message = if let Some(s) = args.message.simple {
199            RequestMessage::Simple(s)
200        } else if let Some(s) = args.message.inline {
201            let mut de = serde_json::Deserializer::from_str(&s);
202            let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
203                crate::cli::command::FromArgsError {
204                    field: "inline",
205                    source: source.into(),
206                }
207            })?;
208            RequestMessage::Inline(v)
209        } else if let Some(p) = args.message.file {
210            RequestMessage::File(p)
211        } else if let Some(s) = args.message.python_inline {
212            RequestMessage::PythonInline(s)
213        } else {
214            // Clap `required = true` on `MessageArgs` guarantees
215            // exactly one of the five flags is set.
216            RequestMessage::PythonFile(args.message.python_file.unwrap())
217        };
218        let agent = AgentSelector::try_from(args.agent)?;
219        let dangerous_advanced: Option<RequestDangerousAdvanced> =
220            if let Some(s) = args.dangerous_advanced {
221                let mut de = serde_json::Deserializer::from_str(&s);
222                let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
223                    crate::cli::command::FromArgsError {
224                        field: "dangerous_advanced",
225                        source: source.into(),
226                    }
227                })?;
228                Some(v)
229            } else {
230                None
231            };
232        Ok(Self {
233            path_type: Path::AgentsMessage,
234            agent,
235            message,
236            dangerous_advanced,
237            base: args.base.into(),
238        })
239    }
240}
241
242#[cfg(feature = "cli-executor")]
243pub async fn execute<E: crate::cli::command::CommandExecutor>(
244    executor: &E,
245    mut request: Request,
246
247        agent_arguments: Option<&crate::cli::command::AgentArguments>,
248    ) -> Result<Response, E::Error> {
249    request.base.clear_transform();
250    executor.execute_one(request, agent_arguments).await
251}
252
253#[cfg(feature = "cli-executor")]
254pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
255    executor: &E,
256    mut request: Request,
257    transform: crate::cli::command::Transform,
258
259        agent_arguments: Option<&crate::cli::command::AgentArguments>,
260    ) -> Result<serde_json::Value, E::Error> {
261    request.base.set_transform(transform);
262    executor.execute_one(request, agent_arguments).await
263}
264
265#[cfg(feature = "mcp")]
266impl crate::cli::command::CommandResponse for Response {
267    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
268        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
269    }
270}
271
272pub mod request_schema;
273
274pub mod response_schema;
275
276/// One `/listen` broadcast run of `agents message`: the actual
277/// [`Request`], the producer's
278/// [`AgentArguments`](crate::cli::command::AgentArguments), and the
279/// unary response future. See [`crate::cli::broadcast_listener`].
280#[cfg(feature = "cli-listener")]
281pub struct ListenerExecution {
282    pub request: Request,
283    pub agent_arguments: crate::cli::command::AgentArguments,
284    pub response: crate::cli::broadcast_listener::UnaryResponse<Response>,
285}