Skip to main content

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

1//! `agents spawn` — async handler stub.
2
3use crate::cli::command::CommandRequest;
4use crate::cli::command::agents::message::RequestMessage;
5use crate::cli::command::agents::selector::AgentSelector;
6
7#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
8#[schemars(rename = "cli.command.agents.spawn.Request")]
9pub struct Request {
10    pub path_type: Path,
11    /// Initial user message. The CLI turns it into a single
12    /// `Message::User` at the head of the `messages` array on the
13    /// API call. Same wire shape as `agents message`'s
14    /// `RequestMessage` — `Simple`, `Inline(RichContent)`,
15    /// `File`, `PythonInline`, `PythonFile`.
16    pub message: RequestMessage,
17    /// What to spawn — a direct agent ref (inline / file / python /
18    /// remote), an existing tag (a GROUPED tag's group flips to
19    /// BOUND on the spawn's `agent_instance_hierarchy` via the
20    /// conduit-driven upgrade; a BOUND tag resumes its live
21    /// hierarchy), or an existing agent instance (resumed via its
22    /// stored session + continuation). Same shape as
23    /// `agents message`'s `agent`.
24    pub agent: AgentSelector,
25    pub dangerous_advanced: Option<RequestDangerousAdvanced>,
26    #[serde(flatten)]
27    pub base: crate::cli::command::RequestBase,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
31#[schemars(rename = "cli.command.agents.spawn.Path")]
32pub enum Path {
33    #[serde(rename = "agents/spawn")]
34    AgentsSpawn,
35}
36
37impl CommandRequest for Request {
38    fn request_base(&self) -> &crate::cli::command::RequestBase {
39        &self.base
40    }
41
42    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
43        Some(&mut self.base)
44    }
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
48#[schemars(rename = "cli.command.agents.spawn.RequestDangerousAdvanced")]
49pub struct RequestDangerousAdvanced {
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    #[schemars(extend("omitempty" = true))]
52    pub stream: Option<bool>,
53    /// Deterministic seed for the upstream model's RNG (mock
54    /// agents in particular). Plumbed onto
55    /// `AgentCompletionCreateParams.seed`. `None` here ⇒ the
56    /// api picks; tests should always pin a value.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    #[schemars(extend("omitempty" = true))]
59    pub seed: Option<i64>,
60}
61
62#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
63#[serde(untagged)]
64#[schemars(rename = "cli.command.agents.spawn.ResponseItem")]
65pub enum ResponseItem {
66    #[schemars(title = "Chunk")]
67    Chunk(crate::agent::completions::response::streaming::AgentCompletionChunk),
68    #[schemars(title = "Id")]
69    Id(String),
70}
71
72/// Non-chunk variant of [`ResponseItem`]. Returned by the unary `execute`
73/// path (with `dangerous_advanced.stream` cleared) when the cli emits a
74/// single bare id string.
75pub type Response = String;
76
77#[derive(clap::Args)]
78pub struct Args {
79    #[command(flatten)]
80    pub message: MessageArgs,
81    #[command(flatten)]
82    pub agent: crate::cli::command::agents::selector::AgentSelectorArgs,
83    /// Raw JSON for `RequestDangerousAdvanced` (e.g.
84    /// `{"stream":true,"seed":42}`).
85    #[arg(long)]
86    pub dangerous_advanced: Option<String>,
87    #[command(flatten)]
88    pub base: crate::cli::command::RequestBaseArgs,
89}
90
91/// Required user-message group. Mirrors `agents instances
92/// message`'s shape: exactly one of the five flags must be set.
93#[derive(clap::Args)]
94#[group(required = true, multiple = false)]
95pub struct MessageArgs {
96    /// Plain text — becomes the body of a single user message.
97    #[arg(long)]
98    pub simple: Option<String>,
99    /// Inline JSON `RichContent`.
100    #[arg(long)]
101    pub inline: Option<String>,
102    /// Path to a JSON file containing the rich content.
103    #[arg(long)]
104    pub file: Option<std::path::PathBuf>,
105    /// Inline Python code that produces the rich content.
106    #[arg(long)]
107    pub python_inline: Option<String>,
108    /// Path to a Python file that produces the rich content.
109    #[arg(long)]
110    pub python_file: Option<std::path::PathBuf>,
111}
112
113#[derive(clap::Args)]
114#[command(args_conflicts_with_subcommands = true)]
115pub struct Command {
116    #[command(flatten)]
117    pub args: Args,
118    #[command(subcommand)]
119    pub schema: Option<Schema>,
120}
121
122#[derive(clap::Subcommand)]
123pub enum Schema {
124    /// Emit the JSON Schema for this leaf's `Request` type and exit.
125    RequestSchema(request_schema::Args),
126    /// Emit the JSON Schema for this leaf's `Response` type and exit.
127    ResponseSchema(response_schema::Args),
128}
129
130impl TryFrom<Args> for Request {
131    type Error = crate::cli::command::FromArgsError;
132    fn try_from(args: Args) -> Result<Self, Self::Error> {
133        let message = if let Some(s) = args.message.simple {
134            RequestMessage::Simple(s)
135        } else if let Some(s) = args.message.inline {
136            let mut de = serde_json::Deserializer::from_str(&s);
137            let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
138                crate::cli::command::FromArgsError {
139                    field: "inline",
140                    source: source.into(),
141                }
142            })?;
143            RequestMessage::Inline(v)
144        } else if let Some(p) = args.message.file {
145            RequestMessage::File(p)
146        } else if let Some(s) = args.message.python_inline {
147            RequestMessage::PythonInline(s)
148        } else {
149            // Clap `required = true` on the `MessageArgs` group
150            // guarantees exactly one of the five flags is set.
151            RequestMessage::PythonFile(args.message.python_file.unwrap())
152        };
153        let agent = AgentSelector::try_from(args.agent)?;
154        let dangerous_advanced: Option<RequestDangerousAdvanced> =
155            if let Some(s) = args.dangerous_advanced {
156                let mut de = serde_json::Deserializer::from_str(&s);
157                let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
158                    crate::cli::command::FromArgsError {
159                        field: "dangerous_advanced",
160                        source: source.into(),
161                    }
162                })?;
163                Some(v)
164            } else {
165                None
166            };
167        Ok(Self { path_type: Path::AgentsSpawn,
168            message,
169            agent,
170            dangerous_advanced,
171            base: args.base.into(),
172        })
173    }
174}
175
176#[cfg(feature = "cli-executor")]
177pub async fn execute_streaming<E: crate::cli::command::CommandExecutor>(
178    executor: &E,
179    mut request: Request,
180
181        agent_arguments: Option<&crate::cli::command::AgentArguments>,
182    ) -> Result<E::Stream<ResponseItem>, E::Error> {
183    request.base.clear_transform();
184    let mut advanced = request.dangerous_advanced.unwrap_or_default();
185    advanced.stream = Some(true);
186    request.dangerous_advanced = Some(advanced);
187    executor.execute(request, agent_arguments).await
188}
189
190#[cfg(feature = "cli-executor")]
191pub async fn execute_streaming_transform<E: crate::cli::command::CommandExecutor>(
192    executor: &E,
193    mut request: Request,
194    transform: crate::cli::command::Transform,
195
196        agent_arguments: Option<&crate::cli::command::AgentArguments>,
197    ) -> Result<E::Stream<serde_json::Value>, E::Error> {
198    request.base.set_transform(transform);
199    let mut advanced = request.dangerous_advanced.unwrap_or_default();
200    advanced.stream = Some(true);
201    request.dangerous_advanced = Some(advanced);
202    executor.execute(request, agent_arguments).await
203}
204
205#[cfg(feature = "cli-executor")]
206pub async fn execute<E: crate::cli::command::CommandExecutor>(
207    executor: &E,
208    mut request: Request,
209
210        agent_arguments: Option<&crate::cli::command::AgentArguments>,
211    ) -> Result<Response, E::Error> {
212    request.base.clear_transform();
213    if let Some(advanced) = request.dangerous_advanced.as_mut() {
214        advanced.stream = None;
215    }
216    executor.execute_one(request, agent_arguments).await
217}
218
219#[cfg(feature = "cli-executor")]
220pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
221    executor: &E,
222    mut request: Request,
223    transform: crate::cli::command::Transform,
224
225        agent_arguments: Option<&crate::cli::command::AgentArguments>,
226    ) -> Result<serde_json::Value, E::Error> {
227    request.base.set_transform(transform);
228    if let Some(advanced) = request.dangerous_advanced.as_mut() {
229        advanced.stream = None;
230    }
231    executor.execute_one(request, agent_arguments).await
232}
233
234#[cfg(feature = "mcp")]
235impl crate::cli::command::CommandResponse for ResponseItem {
236    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
237        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
238    }
239}
240
241pub mod request_schema;
242
243pub mod response_schema;
244
245/// One `/listen` broadcast run of `agents spawn` in its unary
246/// form (the plain `execute`): the actual [`Request`], the
247/// producer's
248/// [`AgentArguments`](crate::cli::command::AgentArguments), and the
249/// unary response future. See [`crate::cli::websocket_listener`].
250#[cfg(feature = "cli-listener")]
251pub struct ListenerExecution {
252    pub request: Request,
253    pub agent_arguments: crate::cli::command::AgentArguments,
254    pub response: crate::cli::websocket_listener::UnaryResponse<Response>,
255}
256
257/// One `/listen` broadcast run of `agents spawn` in its
258/// streaming form (`execute_streaming` — the request set
259/// `dangerous_advanced.stream: true`): the actual [`Request`], the
260/// producer's
261/// [`AgentArguments`](crate::cli::command::AgentArguments), and the
262/// response-item stream. See [`crate::cli::websocket_listener`].
263#[cfg(feature = "cli-listener")]
264pub struct ListenerExecutionStreaming {
265    pub request: Request,
266    pub agent_arguments: crate::cli::command::AgentArguments,
267    pub response: crate::cli::websocket_listener::ResponseItemStream<ResponseItem>,
268}
269
270/// This leaf's multiple listener executions — one variant per
271/// execute fn (`Execution` for the plain `execute`, `Streaming`
272/// for `execute_streaming`), discriminated per request off
273/// `dangerous_advanced.stream`. The branch enum's single variant
274/// for this leaf wraps this.
275#[cfg(feature = "cli-listener")]
276pub enum ListenerExecutionVariant {
277    Execution(ListenerExecution),
278    Streaming(ListenerExecutionStreaming),
279}