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    /// `Some(true)` → skip the INITIAL agent/tag lock acquisition
61    /// at stream start. Set by `agents message` after transferring
62    /// its own claim into this process (re-acquiring would fail
63    /// against the very handles this process inherited; the lock
64    /// lives until this process exits). Mid-stream best-effort AIH
65    /// claims are unaffected by this flag.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    #[schemars(extend("omitempty" = true))]
68    pub skip_lock: Option<bool>,
69}
70
71#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
72#[serde(untagged)]
73#[schemars(rename = "cli.command.agents.spawn.ResponseItem")]
74pub enum ResponseItem {
75    #[schemars(title = "Chunk")]
76    Chunk(crate::agent::completions::response::streaming::AgentCompletionChunk),
77    #[schemars(title = "Id")]
78    Id(String),
79}
80
81/// Non-chunk variant of [`ResponseItem`]. Returned by the unary `execute`
82/// path (with `dangerous_advanced.stream` cleared) when the cli emits a
83/// single bare id string.
84pub type Response = String;
85
86#[derive(clap::Args)]
87pub struct Args {
88    #[command(flatten)]
89    pub message: MessageArgs,
90    #[command(flatten)]
91    pub agent: crate::cli::command::agents::selector::AgentSelectorArgs,
92    /// Raw JSON for `RequestDangerousAdvanced` (e.g.
93    /// `{"stream":true,"seed":42}`).
94    #[arg(long)]
95    pub dangerous_advanced: Option<String>,
96    #[command(flatten)]
97    pub base: crate::cli::command::RequestBaseArgs,
98}
99
100/// Required user-message group. Mirrors `agents instances
101/// message`'s shape: exactly one of the five flags must be set.
102#[derive(clap::Args)]
103#[group(required = true, multiple = false)]
104pub struct MessageArgs {
105    /// Plain text — becomes the body of a single user message.
106    #[arg(long)]
107    pub simple: Option<String>,
108    /// Inline JSON `RichContent`.
109    #[arg(long)]
110    pub inline: Option<String>,
111    /// Path to a JSON file containing the rich content.
112    #[arg(long)]
113    pub file: Option<std::path::PathBuf>,
114    /// Inline Python code that produces the rich content.
115    #[arg(long)]
116    pub python_inline: Option<String>,
117    /// Path to a Python file that produces the rich content.
118    #[arg(long)]
119    pub python_file: Option<std::path::PathBuf>,
120}
121
122#[derive(clap::Args)]
123#[command(args_conflicts_with_subcommands = true)]
124pub struct Command {
125    #[command(flatten)]
126    pub args: Args,
127    #[command(subcommand)]
128    pub schema: Option<Schema>,
129}
130
131#[derive(clap::Subcommand)]
132pub enum Schema {
133    /// Emit the JSON Schema for this leaf's `Request` type and exit.
134    RequestSchema(request_schema::Args),
135    /// Emit the JSON Schema for this leaf's `Response` type and exit.
136    ResponseSchema(response_schema::Args),
137}
138
139impl TryFrom<Args> for Request {
140    type Error = crate::cli::command::FromArgsError;
141    fn try_from(args: Args) -> Result<Self, Self::Error> {
142        let message = if let Some(s) = args.message.simple {
143            RequestMessage::Simple(s)
144        } else if let Some(s) = args.message.inline {
145            let mut de = serde_json::Deserializer::from_str(&s);
146            let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
147                crate::cli::command::FromArgsError {
148                    field: "inline",
149                    source: source.into(),
150                }
151            })?;
152            RequestMessage::Inline(v)
153        } else if let Some(p) = args.message.file {
154            RequestMessage::File(p)
155        } else if let Some(s) = args.message.python_inline {
156            RequestMessage::PythonInline(s)
157        } else {
158            // Clap `required = true` on the `MessageArgs` group
159            // guarantees exactly one of the five flags is set.
160            RequestMessage::PythonFile(args.message.python_file.unwrap())
161        };
162        let agent = AgentSelector::try_from(args.agent)?;
163        let dangerous_advanced: Option<RequestDangerousAdvanced> =
164            if let Some(s) = args.dangerous_advanced {
165                let mut de = serde_json::Deserializer::from_str(&s);
166                let v = serde_path_to_error::deserialize(&mut de).map_err(|source| {
167                    crate::cli::command::FromArgsError {
168                        field: "dangerous_advanced",
169                        source: source.into(),
170                    }
171                })?;
172                Some(v)
173            } else {
174                None
175            };
176        Ok(Self { path_type: Path::AgentsSpawn,
177            message,
178            agent,
179            dangerous_advanced,
180            base: args.base.into(),
181        })
182    }
183}
184
185#[cfg(feature = "cli-executor")]
186pub async fn execute_streaming<E: crate::cli::command::CommandExecutor>(
187    executor: &E,
188    mut request: Request,
189
190        agent_arguments: Option<&crate::cli::command::AgentArguments>,
191    ) -> Result<E::Stream<ResponseItem>, E::Error> {
192    request.base.clear_transform();
193    let mut advanced = request.dangerous_advanced.unwrap_or_default();
194    advanced.stream = Some(true);
195    request.dangerous_advanced = Some(advanced);
196    executor.execute(request, agent_arguments).await
197}
198
199#[cfg(feature = "cli-executor")]
200pub async fn execute_streaming_transform<E: crate::cli::command::CommandExecutor>(
201    executor: &E,
202    mut request: Request,
203    transform: crate::cli::command::Transform,
204
205        agent_arguments: Option<&crate::cli::command::AgentArguments>,
206    ) -> Result<E::Stream<serde_json::Value>, E::Error> {
207    request.base.set_transform(transform);
208    let mut advanced = request.dangerous_advanced.unwrap_or_default();
209    advanced.stream = Some(true);
210    request.dangerous_advanced = Some(advanced);
211    executor.execute(request, agent_arguments).await
212}
213
214#[cfg(feature = "cli-executor")]
215pub async fn execute<E: crate::cli::command::CommandExecutor>(
216    executor: &E,
217    mut request: Request,
218
219        agent_arguments: Option<&crate::cli::command::AgentArguments>,
220    ) -> Result<Response, E::Error> {
221    request.base.clear_transform();
222    if let Some(advanced) = request.dangerous_advanced.as_mut() {
223        advanced.stream = None;
224    }
225    executor.execute_one(request, agent_arguments).await
226}
227
228#[cfg(feature = "cli-executor")]
229pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
230    executor: &E,
231    mut request: Request,
232    transform: crate::cli::command::Transform,
233
234        agent_arguments: Option<&crate::cli::command::AgentArguments>,
235    ) -> Result<serde_json::Value, E::Error> {
236    request.base.set_transform(transform);
237    if let Some(advanced) = request.dangerous_advanced.as_mut() {
238        advanced.stream = None;
239    }
240    executor.execute_one(request, agent_arguments).await
241}
242
243#[cfg(feature = "mcp")]
244impl crate::cli::command::CommandResponse for ResponseItem {
245    fn into_mcp(self) -> crate::cli::command::McpResponseItem {
246        crate::cli::command::McpResponseItem::JSONL(serde_json::to_value(self).unwrap())
247    }
248}
249
250pub mod request_schema;
251
252
253pub mod response_schema;