Skip to main content

objectiveai_sdk/cli/command/python/
mod.rs

1//! `python` — run a Python snippet and return its output as JSON.
2//!
3//! Executes `--code` in the embedded Python runtime with the optional
4//! `--input` JSON value exposed to the script as the global `input`,
5//! and returns the script's output (its trailing expression value,
6//! else captured stdout) as a `serde_json::Value`. No output → JSON
7//! `null`.
8
9use crate::cli::command::CommandRequest;
10
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
12#[schemars(rename = "cli.command.python.Request")]
13pub struct Request {
14    pub path_type: Path,
15    /// Python source to execute.
16    pub code: String,
17    /// Optional JSON value exposed to the code as the global `input`.
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    #[schemars(extend("omitempty" = true))]
20    pub input: Option<serde_json::Value>,
21    #[serde(flatten)]
22    pub base: crate::cli::command::RequestBase,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
26#[schemars(rename = "cli.command.python.Path")]
27pub enum Path {
28    #[serde(rename = "python")]
29    Python,
30}
31
32impl CommandRequest for Request {
33    fn request_base(&self) -> &crate::cli::command::RequestBase {
34        &self.base
35    }
36
37    fn request_base_mut(&mut self) -> Option<&mut crate::cli::command::RequestBase> {
38        Some(&mut self.base)
39    }
40}
41
42/// Whatever the script produced, as raw JSON (no output → `null`).
43pub type Response = serde_json::Value;
44
45#[derive(clap::Args)]
46#[command(group(clap::ArgGroup::new("code_required").required(true).args(["code"])))]
47pub struct Args {
48    /// Python source to execute.
49    #[arg(long)]
50    pub code: Option<String>,
51    /// Optional JSON value exposed to the code as the global `input`.
52    #[arg(long, value_parser = parse_json)]
53    pub input: Option<serde_json::Value>,
54    #[command(flatten)]
55    pub base: crate::cli::command::RequestBaseArgs,
56}
57
58#[derive(clap::Args)]
59#[command(args_conflicts_with_subcommands = true)]
60pub struct Command {
61    #[command(flatten)]
62    pub args: Args,
63    #[command(subcommand)]
64    pub schema: Option<Schema>,
65}
66
67#[derive(clap::Subcommand)]
68pub enum Schema {
69    /// Emit the JSON Schema for this leaf's `Request` type and exit.
70    RequestSchema(request_schema::Args),
71    /// Emit the JSON Schema for this leaf's `Response` type and exit.
72    ResponseSchema(response_schema::Args),
73}
74
75/// `--input` value parser: parse the flag's string as a JSON value.
76fn parse_json(s: &str) -> Result<serde_json::Value, String> {
77    serde_json::from_str(s).map_err(|e| e.to_string())
78}
79
80impl TryFrom<Args> for Request {
81    type Error = crate::cli::command::FromArgsError;
82    fn try_from(args: Args) -> Result<Self, Self::Error> {
83        Ok(Self {
84            path_type: Path::Python,
85            code: args.code.ok_or_else(|| {
86                crate::cli::command::FromArgsError::path_parse(
87                    "code",
88                    "--code is required".to_string(),
89                )
90            })?,
91            input: args.input,
92            base: args.base.into(),
93        })
94    }
95}
96
97#[cfg(feature = "cli-executor")]
98pub async fn execute<E: crate::cli::command::CommandExecutor>(
99    executor: &E,
100    mut request: Request,
101    agent_arguments: Option<&crate::cli::command::AgentArguments>,
102) -> Result<Response, E::Error> {
103    request.base.clear_transform();
104    executor.execute_one(request, agent_arguments).await
105}
106
107#[cfg(feature = "cli-executor")]
108pub async fn execute_transform<E: crate::cli::command::CommandExecutor>(
109    executor: &E,
110    mut request: Request,
111    transform: crate::cli::command::Transform,
112    agent_arguments: Option<&crate::cli::command::AgentArguments>,
113) -> Result<serde_json::Value, E::Error> {
114    request.base.set_transform(transform);
115    executor.execute_one(request, agent_arguments).await
116}
117
118pub mod request_schema;
119
120pub mod response_schema;