Skip to main content

objectiveai_sdk/cli/command/
command.rs

1//! Root-level clap `Command` plus the matching typed `Request` /
2//! `ResponseItem` aggregators and conversions, mirroring the same
3//! pattern every tier `mod.rs` follows for its own subcommands.
4
5#[derive(clap::Subcommand)]
6pub enum Subcommand {
7    Agents {
8        #[command(subcommand)]
9        command: super::agents::Command,
10    },
11    Api {
12        #[command(subcommand)]
13        command: super::api::Command,
14    },
15    Daemon {
16        #[command(subcommand)]
17        command: super::daemon::Command,
18    },
19    Db {
20        #[command(subcommand)]
21        command: super::db::Command,
22    },
23    Functions {
24        #[command(subcommand)]
25        command: super::functions::Command,
26    },
27    Laboratories {
28        #[command(subcommand)]
29        command: super::laboratories::Command,
30    },
31    /// Run a Python snippet and return its output as JSON.
32    Python(super::python::Command),
33    Swarms {
34        #[command(subcommand)]
35        command: super::swarms::Command,
36    },
37    Update(super::update::Command),
38    Channels {
39        #[command(subcommand)]
40        command: super::channels::Command,
41    },
42    Development {
43        #[command(subcommand)]
44        command: super::development::Command,
45    },
46    Tasks {
47        #[command(subcommand)]
48        command: super::tasks::Command,
49    },
50    Viewer {
51        #[command(subcommand)]
52        command: super::viewer::Command,
53    },
54}
55
56#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
57#[serde(untagged)]
58#[schemars(rename = "cli.command.Request")]
59pub enum Request {
60    #[schemars(title = "Agents")]
61    Agents(super::agents::Request),
62    #[schemars(title = "Api")]
63    Api(super::api::Request),
64    #[schemars(title = "Daemon")]
65    Daemon(super::daemon::Request),
66    #[schemars(title = "Db")]
67    Db(super::db::Request),
68    #[schemars(title = "Functions")]
69    Functions(super::functions::Request),
70    #[schemars(title = "Laboratories")]
71    Laboratories(super::laboratories::Request),
72    #[schemars(title = "Python")]
73    Python(super::python::Request),
74    #[schemars(title = "PythonRequestSchema")]
75    PythonRequestSchema(super::python::request_schema::Request),
76    #[schemars(title = "PythonResponseSchema")]
77    PythonResponseSchema(super::python::response_schema::Request),
78    #[schemars(title = "Swarms")]
79    Swarms(super::swarms::Request),
80    #[schemars(title = "Update")]
81    Update(super::update::Request),
82    #[schemars(title = "UpdateRequestSchema")]
83    UpdateRequestSchema(super::update::request_schema::Request),
84    #[schemars(title = "UpdateResponseSchema")]
85    UpdateResponseSchema(super::update::response_schema::Request),
86    #[schemars(title = "Channels")]
87    Channels(super::channels::Request),
88    #[schemars(title = "Development")]
89    Development(super::development::Request),
90    #[schemars(title = "Tasks")]
91    Tasks(super::tasks::Request),
92    #[schemars(title = "Viewer")]
93    Viewer(super::viewer::Request),
94}
95
96// Exempt from json-schema coverage: the aggregate's transitive
97// expansion spans the whole command tree, which downstream
98// generated TypeScript cannot emit declarations for (TS7056), and
99// no consumer uses the aggregate schema — leaf schemas cover the
100// wire.
101#[objectiveai_sdk_macros::json_schema_ignore]
102#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
103#[schemars(rename = "cli.command.ResponseItem")]
104#[serde(untagged)]
105pub enum ResponseItem {
106    #[schemars(title = "Agents")]
107    Agents(super::agents::ResponseItem),
108    #[schemars(title = "Api")]
109    Api(super::api::Response),
110    #[schemars(title = "Daemon")]
111    Daemon(super::daemon::ResponseItem),
112    #[schemars(title = "Db")]
113    Db(super::db::ResponseItem),
114    #[schemars(title = "Functions")]
115    Functions(super::functions::ResponseItem),
116    #[schemars(title = "Laboratories")]
117    Laboratories(super::laboratories::ResponseItem),
118    #[schemars(title = "Python")]
119    Python(serde_json::Value),
120    #[schemars(title = "PythonRequestSchema")]
121    PythonRequestSchema(super::python::request_schema::Response),
122    #[schemars(title = "PythonResponseSchema")]
123    PythonResponseSchema(super::python::response_schema::Response),
124    #[schemars(title = "Swarms")]
125    Swarms(super::swarms::ResponseItem),
126    #[schemars(title = "Update")]
127    Update(super::update::ResponseItem),
128    #[schemars(title = "UpdateRequestSchema")]
129    UpdateRequestSchema(super::update::request_schema::Response),
130    #[schemars(title = "UpdateResponseSchema")]
131    UpdateResponseSchema(super::update::response_schema::Response),
132    #[schemars(title = "Channels")]
133    Channels(super::channels::ResponseItem),
134    #[schemars(title = "Development")]
135    Development(super::development::ResponseItem),
136    #[schemars(title = "Tasks")]
137    Tasks(super::tasks::ResponseItem),
138    #[schemars(title = "Viewer")]
139    Viewer(super::viewer::Response),
140}
141
142#[cfg(feature = "mcp")]
143impl super::CommandResponse for ResponseItem {
144    fn into_mcp(self) -> super::McpResponseItem {
145        match self {
146            ResponseItem::Agents(v) => v.into_mcp(),
147            ResponseItem::Api(v) => v.into_mcp(),
148            ResponseItem::Daemon(v) => v.into_mcp(),
149            ResponseItem::Db(v) => v.into_mcp(),
150            ResponseItem::Functions(v) => v.into_mcp(),
151            ResponseItem::Laboratories(v) => v.into_mcp(),
152            ResponseItem::Python(v) => v.into_mcp(),
153            ResponseItem::PythonRequestSchema(v) => v.into_mcp(),
154            ResponseItem::PythonResponseSchema(v) => v.into_mcp(),
155            ResponseItem::Swarms(v) => v.into_mcp(),
156            ResponseItem::Update(v) => v.into_mcp(),
157            ResponseItem::UpdateRequestSchema(v) => v.into_mcp(),
158            ResponseItem::UpdateResponseSchema(v) => v.into_mcp(),
159            ResponseItem::Channels(v) => v.into_mcp(),
160            ResponseItem::Development(v) => v.into_mcp(),
161            ResponseItem::Tasks(v) => v.into_mcp(),
162            ResponseItem::Viewer(v) => v.into_mcp(),
163        }
164    }
165}
166
167impl TryFrom<Subcommand> for Request {
168    type Error = super::FromArgsError;
169    fn try_from(command: Subcommand) -> Result<Self, Self::Error> {
170        match command {
171            Subcommand::Agents { command } =>
172                Ok(Request::Agents(super::agents::Request::try_from(command)?)),
173            Subcommand::Api { command } =>
174                Ok(Request::Api(super::api::Request::try_from(command)?)),
175            Subcommand::Daemon { command } =>
176                Ok(Request::Daemon(super::daemon::Request::try_from(command)?)),
177            Subcommand::Db { command } =>
178                Ok(Request::Db(super::db::Request::try_from(command)?)),
179            Subcommand::Functions { command } =>
180                Ok(Request::Functions(super::functions::Request::try_from(command)?)),
181            Subcommand::Laboratories { command } =>
182                Ok(Request::Laboratories(super::laboratories::Request::try_from(command)?)),
183            Subcommand::Python(cmd) => match cmd.schema {
184                None => Ok(Request::Python(super::python::Request::try_from(cmd.args)?)),
185                Some(super::python::Schema::RequestSchema(args)) =>
186                    Ok(Request::PythonRequestSchema(super::python::request_schema::Request::try_from(args)?)),
187                Some(super::python::Schema::ResponseSchema(args)) =>
188                    Ok(Request::PythonResponseSchema(super::python::response_schema::Request::try_from(args)?)),
189            },
190            Subcommand::Swarms { command } =>
191                Ok(Request::Swarms(super::swarms::Request::try_from(command)?)),
192            Subcommand::Update(cmd) => match cmd.schema {
193                None => Ok(Request::Update(super::update::Request::try_from(cmd.args)?)),
194                Some(super::update::Schema::RequestSchema(args)) =>
195                    Ok(Request::UpdateRequestSchema(super::update::request_schema::Request::try_from(args)?)),
196                Some(super::update::Schema::ResponseSchema(args)) =>
197                    Ok(Request::UpdateResponseSchema(super::update::response_schema::Request::try_from(args)?)),
198            },
199            Subcommand::Channels { command } =>
200                Ok(Request::Channels(super::channels::Request::try_from(command)?)),
201            Subcommand::Development { command } =>
202                Ok(Request::Development(super::development::Request::try_from(command)?)),
203            Subcommand::Tasks { command } =>
204                Ok(Request::Tasks(super::tasks::Request::try_from(command)?)),
205            Subcommand::Viewer { command } =>
206                Ok(Request::Viewer(super::viewer::Request::try_from(command)?)),
207        }
208    }
209}
210
211impl TryFrom<Command> for Request {
212    type Error = super::FromArgsError;
213    fn try_from(command: Command) -> Result<Self, Self::Error> {
214        match (command.request, command.command) {
215            // `--request <json>`: deserialize straight into the aggregate
216            // Request (serde-tagged on `path_type`) — the same wire shape the
217            // SDKs already serialize. Mutually exclusive with a subcommand
218            // (clap enforces it), so the `_` arm can't carry a command.
219            (Some(json), _) => {
220                let de = &mut serde_json::Deserializer::from_str(&json);
221                serde_path_to_error::deserialize(de)
222                    .map_err(|e| super::FromArgsError::json("request", e))
223            }
224            (None, Some(subcommand)) => Request::try_from(subcommand),
225            // Unreachable in practice: `arg_required_else_help` turns a bare
226            // invocation into a clap help error before conversion.
227            (None, None) => Err(super::FromArgsError::path_parse(
228                "command",
229                "a command path or --request is required".to_string(),
230            )),
231        }
232    }
233}
234
235impl super::CommandRequest for Request {
236    fn request_base(&self) -> &crate::cli::command::RequestBase {
237        match self {
238            Request::Agents(inner) => inner.request_base(),
239            Request::Api(inner) => inner.request_base(),
240            Request::Daemon(inner) => inner.request_base(),
241            Request::Db(inner) => inner.request_base(),
242            Request::Functions(inner) => inner.request_base(),
243            Request::Laboratories(inner) => inner.request_base(),
244            Request::Python(inner) => inner.request_base(),
245            Request::PythonRequestSchema(inner) => inner.request_base(),
246            Request::PythonResponseSchema(inner) => inner.request_base(),
247            Request::Swarms(inner) => inner.request_base(),
248            Request::Update(inner) => inner.request_base(),
249            Request::UpdateRequestSchema(inner) => inner.request_base(),
250            Request::UpdateResponseSchema(inner) => inner.request_base(),
251            Request::Channels(inner) => inner.request_base(),
252            Request::Development(inner) => inner.request_base(),
253            Request::Tasks(inner) => inner.request_base(),
254            Request::Viewer(inner) => inner.request_base(),
255        }
256    }
257
258    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
259        match self {
260            Request::Agents(inner) => inner.request_base_mut(),
261            Request::Api(inner) => inner.request_base_mut(),
262            Request::Daemon(inner) => inner.request_base_mut(),
263            Request::Db(inner) => inner.request_base_mut(),
264            Request::Functions(inner) => inner.request_base_mut(),
265            Request::Laboratories(inner) => inner.request_base_mut(),
266            Request::Python(inner) => inner.request_base_mut(),
267            Request::PythonRequestSchema(inner) => inner.request_base_mut(),
268            Request::PythonResponseSchema(inner) => inner.request_base_mut(),
269            Request::Swarms(inner) => inner.request_base_mut(),
270            Request::Update(inner) => inner.request_base_mut(),
271            Request::UpdateRequestSchema(inner) => inner.request_base_mut(),
272            Request::UpdateResponseSchema(inner) => inner.request_base_mut(),
273            Request::Channels(inner) => inner.request_base_mut(),
274            Request::Development(inner) => inner.request_base_mut(),
275            Request::Tasks(inner) => inner.request_base_mut(),
276            Request::Viewer(inner) => inner.request_base_mut(),
277        }
278    }
279}
280
281#[cfg(feature = "cli-executor")]
282pub async fn execute<E: super::CommandExecutor>(
283    executor: &E,
284    request: Request,
285
286        identity: Option<&crate::identity::Identity>,
287    ) -> Result<
288    std::pin::Pin<Box<dyn futures::Stream<Item = Result<ResponseItem, E::Error>> + Send>>,
289    E::Error,
290> {
291    use futures::StreamExt;
292    let stream: std::pin::Pin<Box<dyn futures::Stream<Item = Result<ResponseItem, E::Error>> + Send>> =
293        match request {
294            Request::Agents(req) => {
295                let inner = super::agents::execute(executor, req, identity).await?;
296                Box::pin(inner.map(|r| r.map(ResponseItem::Agents)))
297            }
298            Request::Api(req) => {
299                let inner = super::api::execute(executor, req, identity).await?;
300                Box::pin(inner.map(|r| r.map(ResponseItem::Api)))
301            }
302            Request::Daemon(req) => {
303                let inner = super::daemon::execute(executor, req, identity).await?;
304                Box::pin(inner.map(|r| r.map(ResponseItem::Daemon)))
305            }
306            Request::Db(req) => {
307                let inner = super::db::execute(executor, req, identity).await?;
308                Box::pin(inner.map(|r| r.map(ResponseItem::Db)))
309            }
310            Request::Functions(req) => {
311                let inner = super::functions::execute(executor, req, identity).await?;
312                Box::pin(inner.map(|r| r.map(ResponseItem::Functions)))
313            }
314            Request::Laboratories(req) => {
315                let inner = super::laboratories::execute(executor, req, identity).await?;
316                Box::pin(inner.map(|r| r.map(ResponseItem::Laboratories)))
317            }
318            Request::Python(req) => {
319                let value = super::python::execute(executor, req, identity).await?;
320                Box::pin(super::StreamOnce::new(Ok(ResponseItem::Python(value))))
321            }
322            Request::PythonRequestSchema(req) => {
323                let value = super::python::request_schema::execute(executor, req, identity).await?;
324                Box::pin(super::StreamOnce::new(Ok(ResponseItem::PythonRequestSchema(value))))
325            }
326            Request::PythonResponseSchema(req) => {
327                let value = super::python::response_schema::execute(executor, req, identity).await?;
328                Box::pin(super::StreamOnce::new(Ok(ResponseItem::PythonResponseSchema(value))))
329            }
330            Request::Swarms(req) => {
331                let inner = super::swarms::execute(executor, req, identity).await?;
332                Box::pin(inner.map(|r| r.map(ResponseItem::Swarms)))
333            }
334            Request::Update(req) => {
335                let inner = super::update::execute(executor, req, identity).await?;
336                Box::pin(inner.map(|r| r.map(ResponseItem::Update)))
337            }
338            Request::UpdateRequestSchema(req) => {
339                let value = super::update::request_schema::execute(executor, req, identity).await?;
340                Box::pin(super::StreamOnce::new(Ok(ResponseItem::UpdateRequestSchema(value))))
341            }
342            Request::UpdateResponseSchema(req) => {
343                let value = super::update::response_schema::execute(executor, req, identity).await?;
344                Box::pin(super::StreamOnce::new(Ok(ResponseItem::UpdateResponseSchema(value))))
345            }
346            Request::Channels(req) => {
347                let inner = super::channels::execute(executor, req, identity).await?;
348                Box::pin(inner.map(|r| r.map(ResponseItem::Channels)))
349            }
350            Request::Development(req) => {
351                let inner = super::development::execute(executor, req, identity).await?;
352                Box::pin(inner.map(|r| r.map(ResponseItem::Development)))
353            }
354            Request::Tasks(req) => {
355                let inner = super::tasks::execute(executor, req, identity).await?;
356                Box::pin(inner.map(|r| r.map(ResponseItem::Tasks)))
357            }
358            Request::Viewer(req) => {
359                let inner = super::viewer::execute(executor, req, identity).await?;
360                Box::pin(inner.map(|r| r.map(ResponseItem::Viewer)))
361            }
362        };
363    Ok(stream)
364}
365
366#[cfg(feature = "cli-executor")]
367pub async fn execute_transform<E: super::CommandExecutor>(
368    executor: &E,
369    request: Request,
370    transform: crate::cli::command::Transform,
371
372        identity: Option<&crate::identity::Identity>,
373    ) -> Result<
374    std::pin::Pin<Box<dyn futures::Stream<Item = Result<serde_json::Value, E::Error>> + Send>>,
375    E::Error,
376> {
377    let stream: std::pin::Pin<Box<dyn futures::Stream<Item = Result<serde_json::Value, E::Error>> + Send>> =
378        match request {
379            Request::Agents(req) => {
380                let inner = super::agents::execute_transform(executor, req, transform, identity).await?;
381                Box::pin(inner)
382            }
383            Request::Api(req) => {
384                let inner = super::api::execute_transform(executor, req, transform, identity).await?;
385                Box::pin(inner)
386            }
387            Request::Daemon(req) => {
388                let inner = super::daemon::execute_transform(executor, req, transform, identity).await?;
389                Box::pin(inner)
390            }
391            Request::Db(req) => {
392                let inner = super::db::execute_transform(executor, req, transform, identity).await?;
393                Box::pin(inner)
394            }
395            Request::Functions(req) => {
396                let inner = super::functions::execute_transform(executor, req, transform, identity).await?;
397                Box::pin(inner)
398            }
399            Request::Laboratories(req) => {
400                let inner = super::laboratories::execute_transform(executor, req, transform, identity).await?;
401                Box::pin(inner)
402            }
403            Request::Python(req) => {
404                let value = super::python::execute_transform(executor, req, transform, identity).await?;
405                Box::pin(super::StreamOnce::new(Ok(value)))
406            }
407            Request::PythonRequestSchema(req) => {
408                let value = super::python::request_schema::execute_transform(executor, req, transform, identity).await?;
409                Box::pin(super::StreamOnce::new(Ok(value)))
410            }
411            Request::PythonResponseSchema(req) => {
412                let value = super::python::response_schema::execute_transform(executor, req, transform, identity).await?;
413                Box::pin(super::StreamOnce::new(Ok(value)))
414            }
415            Request::Swarms(req) => {
416                let inner = super::swarms::execute_transform(executor, req, transform, identity).await?;
417                Box::pin(inner)
418            }
419            Request::Update(req) => {
420                let inner = super::update::execute_transform(executor, req, transform, identity).await?;
421                Box::pin(inner)
422            }
423            Request::UpdateRequestSchema(req) => {
424                let value = super::update::request_schema::execute_transform(executor, req, transform, identity).await?;
425                Box::pin(super::StreamOnce::new(Ok(value)))
426            }
427            Request::UpdateResponseSchema(req) => {
428                let value = super::update::response_schema::execute_transform(executor, req, transform, identity).await?;
429                Box::pin(super::StreamOnce::new(Ok(value)))
430            }
431            Request::Channels(req) => {
432                let inner = super::channels::execute_transform(executor, req, transform, identity).await?;
433                Box::pin(inner)
434            }
435            Request::Development(req) => {
436                let inner = super::development::execute_transform(executor, req, transform, identity).await?;
437                Box::pin(inner)
438            }
439            Request::Tasks(req) => {
440                let inner = super::tasks::execute_transform(executor, req, transform, identity).await?;
441                Box::pin(inner)
442            }
443            Request::Viewer(req) => {
444                let inner = super::viewer::execute_transform(executor, req, transform, identity).await?;
445                Box::pin(inner)
446            }
447        };
448    Ok(stream)
449}
450
451/// Parse an argv slice into a typed [`Request`]. Accepts either
452/// shape:
453///
454/// - With a program-name prefix (`["objectiveai", "agents", "list"]`)
455///   — matches `std::env::args()` and binary entry-point usage.
456/// - Without one (`["agents", "list"]`) — matches
457///   [`super::CommandRequest::into_command`]'s output shape and the
458///   "command-only" shape MCP callers send.
459///
460/// If `args[0]` is `"objectiveai"` we pass it straight through;
461/// otherwise we prepend so clap (which always treats argv[0] as the
462/// program name) sees a well-formed argv. Hides clap behind the SDK
463/// boundary so downstream crates can dispatch arbitrary argv without
464/// taking a clap dep themselves.
465pub fn parse_request(args: &[String]) -> Result<Request, ParseError> {
466    let command = if args.first().map(String::as_str) == Some("objectiveai") {
467        <Command as clap::Parser>::try_parse_from(args)?
468    } else {
469        let argv = std::iter::once("objectiveai".to_string())
470            .chain(args.iter().cloned());
471        <Command as clap::Parser>::try_parse_from(argv)?
472    };
473    Ok(Request::try_from(command)?)
474}
475
476/// Top-level CLI parser: a command path, OR `--request <json>` to execute a
477/// JSON `CliCommandRequest` directly. The two are mutually exclusive
478/// (`args_conflicts_with_subcommands`, enforced natively by clap); a bare
479/// invocation prints help (`arg_required_else_help`). `--request` is a
480/// legitimate but unadvertised programmatic entry point.
481#[derive(clap::Parser)]
482#[command(
483    name = "objectiveai",
484    version,
485    args_conflicts_with_subcommands = true,
486    arg_required_else_help = true
487)]
488pub struct Command {
489    /// Execute this JSON `CliCommandRequest` instead of a command path.
490    /// Mutually exclusive with any command.
491    #[arg(long, value_name = "JSON")]
492    pub request: Option<String>,
493    #[command(subcommand)]
494    pub command: Option<Subcommand>,
495}
496
497/// Error from [`parse_request`]. Either clap rejected the argv
498/// ([`ParseError::Clap`] — `--help`, unknown subcommand, missing
499/// required arg, etc.) or the typed `Command` couldn't be lowered
500/// into a `Request` ([`ParseError::FromArgs`] — inline body JSON
501/// failed to parse, etc.).
502#[derive(Debug)]
503pub enum ParseError {
504    Clap(clap::Error),
505    FromArgs(super::FromArgsError),
506}
507
508impl std::fmt::Display for ParseError {
509    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510        match self {
511            ParseError::Clap(e) => write!(f, "{e}"),
512            ParseError::FromArgs(e) => write!(f, "{e}"),
513        }
514    }
515}
516
517impl std::error::Error for ParseError {}
518
519impl From<clap::Error> for ParseError {
520    fn from(e: clap::Error) -> Self {
521        ParseError::Clap(e)
522    }
523}
524
525impl From<super::FromArgsError> for ParseError {
526    fn from(e: super::FromArgsError) -> Self {
527        ParseError::FromArgs(e)
528    }
529}
530
531/// `/listen` mirror of [`Request`] — the root of the distributed
532/// `ListenerExecution` tree ([`crate::daemon::command_listener`]'s
533/// stream item): one variant per child wrapping its
534/// `ListenerExecution`. The broadcast always carries the typed
535/// PRE-transform items (the producer tee sits below the CLI's
536/// jq/python transform), so every execution lands on its typed
537/// variant. Executions whose `path_type` this build's types predate
538/// are skipped by the listener, so there is no unknown fallback.
539#[cfg(all(feature = "cli", feature = "daemon"))]
540pub enum ListenerExecution {
541    Agents(super::agents::ListenerExecution),
542    Api(super::api::ListenerExecution),
543    Daemon(super::daemon::ListenerExecution),
544    Db(super::db::ListenerExecution),
545    Functions(super::functions::ListenerExecution),
546    Laboratories(super::laboratories::ListenerExecution),
547    Python(super::python::ListenerExecution),
548    PythonRequestSchema(super::python::request_schema::ListenerExecution),
549    PythonResponseSchema(super::python::response_schema::ListenerExecution),
550    Swarms(super::swarms::ListenerExecution),
551    Update(super::update::ListenerExecution),
552    UpdateRequestSchema(super::update::request_schema::ListenerExecution),
553    UpdateResponseSchema(super::update::response_schema::ListenerExecution),
554    Channels(super::channels::ListenerExecution),
555    Development(super::development::ListenerExecution),
556    Tasks(super::tasks::ListenerExecution),
557    Viewer(super::viewer::ListenerExecution),
558}